【问题标题】:Is it possible to replace a word after a phrase using regular expression in php?是否可以在 php 中使用正则表达式替换短语后的单词?
【发布时间】:2018-10-02 21:16:04
【问题描述】:

输入文字:工学院、医学院

所需输出:教育学校,教育学校

规则:后面跟“school of”的任何单词都需要替换为“education”

$inputext = "school of engineering, school of medicine"; 
$rule ="//s/";
$replacetext = "education";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo($outputext);

感谢您的任何建议。

【问题讨论】:

  • 这是一个无效的reges //s/,因为你有一个未转义的分隔符。 preg_replace('/(school of )[-a-z0-9_]+\b/i', '\1'.$replacetext, $inputext)
  • preg_replace("/\\bschool of .+?\\b/", "school of education", $inputext);

标签: php regex preg-replace


【解决方案1】:

无需捕获任何内容或使用环视。

演示:https://3v4l.org/uWZgW

$inputext = "school of engineering, school of medicine"; 
$rule ="/school of \K[a-z]+/";
$replacetext = "education";
$outputext = preg_replace($rule, $replacetext, $inputext);
echo $outputext;

匹配前面的单词(和of后的空格),用\K重新开始全串匹配,然后替换目标单词。

【讨论】:

    【解决方案2】:

    当然,只需在 school of 上使用 positive lookbehind 加上空格:
    (?<=school of )\w+

    • (?<=school of ) 匹配 school of 和空格之后的任何内容。
    • \w 表示任意单词字符,+ 表示介于 1 和无限个之间。

    所以你的代码是:

    $inputext = "school of engineering, school of medicine"; 
    $rule ="/(?<=school of )\w+/";
    $replacetext = "education";
    $outputext = preg_replace($rule, $replacetext, $inputext);
    echo($outputext);
    

    哪些输出:

    教育学院,教育学院

    这可以在 Regex101 here 和 3val here 上看到。

    【讨论】:

    • 是的。我已经删除了它,简化了正则表达式:)
    • 我知道我没有在问题中问这个。我怎样才能推特你的代码来照顾,比如工程学校,医学院 -> 教育学校?
    猜你喜欢
    • 1970-01-01
    • 2013-11-09
    • 2020-05-21
    • 1970-01-01
    • 2010-09-27
    • 1970-01-01
    • 2022-12-10
    • 2020-01-06
    • 1970-01-01
    相关资源
    最近更新 更多