簡體   English   中英

從php中的字符串替換可選的單詞/表達式

[英]Replace an optional word / expression from a string in php

如何從php中的給定字符串中替換以下可選單詞/表達式?

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

現在我要替換給定單詞中的表達式- Client Side:Client Side :兩者之間的區別是,一個單詞以冒號$word:結尾$word:另一個$word:以多余的空格和冒號$word :結尾$word :

因此,我該如何編寫regeX來解決此問題。 我已經嘗試過使用str_replace ,但是這樣做會使用多個str_replace 我希望使用preg_replace干凈簡單的regeX替換給定的表達式。

您可以簡單地使用以下正則表達式

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

在這里,我使用了\\bClient Side\\s?:\\B正則表達式。 在這個正則表達式\\s? 將檢查是否有可選空格,如果是,則同時獲取其匹配項,如果不匹配,則還將匹配給定的字符串以及單詞邊界

正則表達式

演示版

您可以按以下方式使用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

有關參數的簡要說明,請參閱以下URL- http://www.hackingwithphp.com/4/8/6/regular-expression-syntax-examples

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM