PHP正则表达式查找并替换为新字符串

时间:2015-08-23 17:58:50

标签: php regex

我有一个字符串,其中包含:

[quote name="username" url="/t/44223/topics-name#post_734738"]

我想写一个php正则表达式,它会找到这个字符串的所有出现并找到帖子号码(例如734738),然后用以下内容替换整个事件:

[quote=username;new post number based on 734738]

要求:

  1. 只有以'/ t /'开头且以'#post_ {number}'结尾的网址。
  2. 通过'基于734738的新帖子编号'表示这将是我将从数据库生成的自定义帖子编号。
  3. 请帮帮我。感谢。

    最终答案:

    如果有人需要,这是最终答案:)

    $string = '[quote name="user343I_nsdfdame" url="/t/44223/topics-name#post_734738"]What is your name?[/quote][quote name="username" url="/t/45454/topics-name#post_767676"]Test string[/quote]The quick brown fox....';
    
    if(preg_match_all("/\[quote name=\"([^\"]*)\" url=\"\/t\/[^#]*#post_([0-9]*)\"\]/", $string, $matches)) {
        foreach ($matches[0] as $match) {
            if(preg_match("/\[quote name=\"([^\"]*)\" url=\"\/t\/[^#]*#post_([0-9]*)\"\]/",$match, $reg)) {
                $new = "[quote=".$reg[1].";".$reg[2]."]"; // I have changed $reg[2] according to my need.
                $string = str_replace($match, $new, $string);
            }   
        }
    }
    
    echo $string;
    

    输出:

    [quote=user343I_nsdfdame;734738]What is your name?[/quote][quote=username;767676]Test string[/quote]The quick brown fox....
    

1 个答案:

答案 0 :(得分:2)

这样做:

$string = '[quote name="username" url="/t/44223/topics-name#post_734738"]';
$new = "";
if(preg_match("/\[quote name=\"([^\"]*)\" url=\"\/t\/[^#]*#post_([0-9]*)\"\]/",$string,$reg)) {
    $new = "[quote=".$reg[1].";new post number based on ".$reg[2]."]";
}
echo $new;

输出是:

[quote=username;new post number based on 734738]