【问题标题】:Replace a keyword in Regular Expressions (PCRE) [duplicate]替换正则表达式(PCRE)中的关键字[重复]
【发布时间】:2016-08-16 19:24:32
【问题描述】:

我刚刚开始在 PCRE 中学习正则表达式,并尝试编写一个正则表达式来将字符串中的关键字“men”替换为“women”。 基本上,字符串是一个包含“男人”的文本(不区分大小写),我想用“女人”替换它 非常感谢您的帮助。

【问题讨论】:

  • 这是最基本的正则表达式..你试过什么?
  • 推荐这么简单的str_replace()

标签: php regex pcre


【解决方案1】:

考虑这个正则表达式的解释:

<?php
$string = "This is a man's world and it wouldn't be nothing without a woman or a girl.";
$regex = '~     # opening delimiter
            \b  # word boundary
            man # man literally
            \b  # word boundary
          ~x';  # closing delimiter

echo preg_replace($regex, "woman", $string);
# This is a woman's world and it wouldn't be nothing without a woman or a girl.
?>

正如 cmets 中已经提到的,对于您的具体示例,简单的字符串函数可能更合适。
要真正学习正则表达式,StackOverflow 可能不是最合适的地方,初学者最好选择 http://www.regular-expressions.info 或 http://www.regexone.com .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多