首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用新字符串查找和替换PHP regex

用新字符串查找和替换PHP regex
EN

Stack Overflow用户
提问于 2015-08-23 17:58:50
回答 1查看 66关注 0票数 1

我有一个字符串,它包含:

代码语言:javascript
复制
[quote name="username" url="/t/44223/topics-name#post_734738"]

我想要编写一个php regex,它将查找这个字符串的所有出现,并找到post编号(ex )。( 734738)然后用以下文字替换整个事物:

代码语言:javascript
复制
[quote=username;new post number based on 734738]

要求:

  1. 只有以'/t/‘开头,以'#post_{number}’结尾的URL。
  2. 根据“基于734738的新帖子号”,这将是我从数据库中生成的自定义帖子号。

请帮帮我。谢谢。

最后答案:

如果有人需要这样做,这是最后的答案:)

代码语言:javascript
复制
$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;

输出:

代码语言:javascript
复制
[quote=user343I_nsdfdame;734738]What is your name?[/quote][quote=username;767676]Test string[/quote]The quick brown fox....
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-23 18:20:51

这样可以做到:

代码语言:javascript
复制
$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;

产出如下:

代码语言:javascript
复制
[quote=username;new post number based on 734738]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32169729

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档