Friday 15 May 2015

php - how to REGEX a url and autoadd [url] tag and fix repeat -



php - how to REGEX a url and autoadd [url] tag and fix repeat -

i need function auto add together bbcode.

users utilize editor type something. after submit, run autolink() php function. if content text have url auto add together [url] xxx [/url]

i can it. bbcode editor maybe utilize 2 format url

a. [url]xx[/url] b. [url=xxx] xxx[/url]

i can't prepare repeat problem. here's demo code

$content=" http://www.google.com/logo.png [url]http://www.yahoo.com[/url] [url=http://yahoo.com/abc.zip]download[/url]"; $content = nl2br($content); echo linkadd($content); //auto add together link function linkadd($content){ preg_match_all('~\[url=((?:ftp|https?)://.*?)\](.*?)\[/url\]~s', $content, $stack); foreach($stack[1] $t) { $content = preg_replace('~\[url=((?:ftp|https?)://.*?)\](.*?)\[/url\]~s','[url=\\1]\\2[/url]', $content,1); } preg_match_all('~\[url](.*?)\[/url\]~s', $content, $stack); foreach($stack[1] $t) { $content = preg_replace('~\[url](.*?)\[/url\]~s',$t, $content,1); } $str=preg_replace('(((f|ht){1}tp://)[-a-za-z0-9@:%_/+.~#?&//=]+)','[url]\\0[/url]',$content); homecoming $str; }

now results

[url]http://www.google.com/logo.png[/url] [url]http://www.yahoo.com[/url] [url=[url]http://yahoo.com/abc.zip[/url]]download[/url]

line 1 , line 2 ok.

but line 3 repeat 1 time again [url]xxx[/url]

how [url=[url]http://yahoo.com/abc.zip[/url]]download[/url] [url=http://yahoo.com/abc.zip]download[/url]

code [img] processing without protocol check :

<?php $content="http://www.google.com/logo.png [url]http://www.yahoo.com[/url] [url=http://yahoo.com/abc.zip]download[/url] [img]google.com/logo.png[/img]"; //$content="[img]google.com/logo.png[/img]"; //$content = nl2br($content); echo linkadd($content); echo php_eol; //auto add together link function linkadd($content) { $pattern ='( (?:\[url\])? ( (?<!url=) (?:f|ht)tps?:// [-a-z0-9@:%_/+.~#?&=]+ ) (?:\[/url\])? )xi'; $str=preg_replace($pattern,'[url]$1[/url]',$content); $pattern ='( (?:\[img\]) ([-a-z0-9@:%_/+.~#?&=]+) (?:\[/img\]) )xi'; $str=preg_replace($pattern,'[img][url]$1[/url][/img]',$content); homecoming $str; }

php regex bbcode

No comments:

Post a Comment