【问题标题】:Replace an optional word / expression from a string in php从php中的字符串替换可选的单词/表达式
【发布时间】:2015-09-24 11:59:48
【问题描述】:

如何从 php 中的给定字符串中替换以下可选单词/表达式?

给定字符串 - Client Side: ABC ClientClient Side : XYZ Client

现在我想替换给定单词中的表达式 - Client Side:Client Side : 两者的区别在于,一个单词以冒号结尾$word:,另一个以额外的空格和冒号结尾$word :

那么我该如何编写一个正则表达式来解决这个问题。 ? 我曾尝试使用str_replace,但它会使用多个str_replace 来做到这一点。我想要一个干净简单的正则表达式,使用preg_replace 来替换给定的表达式。

【问题讨论】:

    标签: php regex preg-replace str-replace


    【解决方案1】:

    您可以简单地使用以下正则表达式

    preg_replace('/\bClient Side\s?:\B/','',$str);
    

    这里我使用了\bClient Side\s?:\B 正则表达式。在这个正则表达式中\s? 将检查可选空间,如果是,那么它的 get 匹配,如果不是,那么它也会匹配给定的字符串以及单词边界

    Regex

    Demo

    【讨论】:

    • 你为什么在冒号后面使用\B
    【解决方案2】:

    您可以通过以下方式使用preg_replace来解决问题。

    $string = "Client Side: ABC System"; //either this string or 2nd string
    $string = "Client SideL : XYZ System";
    
    preg_replace("/Client Site[ ]*[:]/", '', $string)
    

    使用的参数说明 -

    /Client Side        # Start searching with this word
    [ ]                 # An optional blank space parameter
    *                   # Any number of occurrence of blank space
    [:]                 # Replace colon when it occurs
    

    参数简要说明请参考以下网址-http://www.hackingwithphp.com/4/8/6/regular-expression-syntax-examples

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      • 2018-07-07
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多