【发布时间】: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]
要求:
- 仅以“/t/”开头并以“#post_{number}”结尾的 URL。
- “基于 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 正则表达式的了解为零。所以我希望有人给我写一个正则表达式。
-
好吧,你至少应该努力研究它并尝试一些东西,然后再期待有人会花时间免费编写你的代码。
-
实际上我正在学习正则表达式,老实说我很开心。真是了不起的事情。对不起,下次我会先学习并发布问题:)