【问题标题】:String Replace a word that is between special characters [duplicate]字符串替换特殊字符之间的单词[重复]
【发布时间】:2017-11-04 21:17:55
【问题描述】:
$text_string = "One One One,One.One OneTwo, Onetwo .Onetwo TwoOne One";

我想用单独或特殊字符之间或字符串开头/结尾的“三”替换单词“一”。 有人有想法吗?

结果必须是:

$text_string = "Three Three Three,Three.Three OneTwo, Onetwo .Onetwo TwoOne Three";

【问题讨论】:

    标签: php regex str-replace


    【解决方案1】:

    您可以使用\b 来检查单词边界:

    $str = 'One One One,One.One OneTwo, Onetwo .Onetwo';
    $replaced = preg_replace('/\bOne\b/', 'Three', $str);
    echo $replaced; // Three Three Three,Three.Three OneTwo, Onetwo .Onetwo TwoOne Three
    

    【讨论】:

    • 现在区分大小写了吗?
    • 如果你想要它,在正则表达式后面添加一个i/\\bOne\\b/i
    • 你为什么放\\b,而不是\b——见regex101.com/r/O7C3cl/1
    • c'n'p 错误,谢谢
    • 不能用这个$returnValue = preg_replace('/\bÜber\b/i', 'Three', 'One Über One,One.Über one OneTwo, Onetwo .Onetwo TwoOne Über', -1);替换包含Ü,Ä,Ö的单词
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    • 2015-03-03
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2016-05-05
    • 2016-09-21
    相关资源
    最近更新 更多