开发者

Need help with REGEX in PHP. A simple one. Help!

Recently, I'm playing with something related to BBCode in phpBB3. When I trace back my database, the posts table and for a random post. I found that the image tag is written this way [img:fcjsgy5j]. There are 8 random characters generated between [img: ... ] for each p开发者_JAVA百科ost.

[img:fcjsgy5j]http://imageurl.jpg[/img]

My question is, how can I make use of preg_replace() to replace the random characters into this way..

<img src="http://imageurl.jpg">


$output = preg_replace("`\[img:.+?\](.*?)\[/img\]`i", '<img src="$1"/>', $input);
  • [ begins a character set. We don't want that; we want to match the literal [ character, so we have to escape it with a \
  • . matches any character
  • + means we match 1 or more of the previous thing (any character)
  • ? makes the previous quantifier ungreedy (.+ would match everything, right to the very end of the string, that's not what we want, we want it to match as little as possible... just up to the next ]
  • (.*?) matches all the junk between the [img] tags. Ungreedy again. We put () around it to make it mtaching set
  • The ` (back-tick) at the start and the end could be any character... whatever character you start with, you have to end with. A lot of people use / but I prefer the back-tick because it rarely appears anywhere inside the regular expression, thus I don't need to escape it.
  • The i at the very end means The expression will be case insensitive. (will match img, IMG, ImG, etc.)
  • The $1 in the replace refers back to the () section we denoted earlier... it basically takes whatever was matched there, and plops it into the place of $1


$result = preg_replace('%\[img:[^]]+\]([^[]+)\[/img\]%', '<img src="\1">', $subject);

or, as a commented regex:

$result = preg_replace(
    '%\[img:  # match [img:
    [^]]+     # match one or more non-] characters
    \]        # match ]
    ([^[]+)   # match one or more non-[ characters
    \[/img\]  # match [/img]
    %x', 
    '<img src="\1">', $subject);


Try this code :

<?php
$search = array(
    '\[img:.+?\](.*?)\[\/img\]\'
);
$replace = array(
    '<img src="\\2">'
);
$result = preg_replace($search, $replace, $string);
}
?>

I used the array form of preg_replace so that u can add more search and replace patterns in the future. I think you are trying to replace some BBCODE tags. There is plenty of libraries on the net to handle BBCODE correctly.

Edited

Like this one : http://php.net/manual/en/book.bbcode.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜