【问题标题】:PHP regex find and replace with new stringPHP正则表达式查找并替换为新字符串
【发布时间】:2015-08-23 17:58:50
【问题描述】:

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

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

我想编写一个 php 正则表达式,它会找到该字符串的所有出现并找到帖子编号(例如 734738),然后将整个内容替换为:

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

要求:

  1. 仅以“/t/”开头并以“#post_{number}”结尾的 URL。
  2. “基于 734738 的新帖子编号”表示这将是我将从数据库生成的自定义帖子编号。

请帮帮我。谢谢。

最终答案:

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

$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....

【问题讨论】:

  • 你试过的代码在哪里?
  • 其实我对 php 正则表达式的了解为零。所以我希望有人给我写一个正则表达式。
  • 好吧,你至少应该努力研究它并尝试一些东西,然后再期待有人会花时间免费编写你的代码。
  • 实际上我正在学习正则表达式,老实说我很开心。真是了不起的事情。对不起,下次我会先学习并发布问题:)

标签: php regex


【解决方案1】:

这样就可以了:

$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]

【讨论】:

  • 您的编码器是正确的,但对于多次出现,我认为我必须使用 'preg_match_all' 函数。无论如何谢谢:)
猜你喜欢
  • 1970-01-01
  • 2014-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
  • 2016-05-14
  • 1970-01-01
相关资源
最近更新 更多