[英]Replace an optional word / expression from a string in php
如何從php中的給定字符串中替換以下可選單詞/表達式?
給定字符串- Client Side: ABC Client
或Client Side : XYZ Client
現在我要替換給定單詞中的表達式- Client Side:
或Client Side :
兩者之間的區別是,一個單詞以冒號$word:
結尾$word:
另一個$word:
以多余的空格和冒號$word :
結尾$word :
因此,我該如何編寫regeX來解決此問題。 ? 我已經嘗試過使用str_replace
,但是這樣做會使用多個str_replace
。 我希望使用preg_replace
干凈簡單的regeX替換給定的表達式。
您可以按以下方式使用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.