替换正则表达式 (PCRE) 中的关键字


Replace a keyword in Regular Expressions (PCRE)

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

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

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

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