![](/img/trans.png)
[英]Regex expression to replace a word between two differents words in a string
[英]Get and replace words in string that contains ? in between of word in string php regex
我如何使用php regex實現以下目的:
我有一個包含以下內容的字符串:
$ a =“ Foo喜歡Bar嗎?我不這樣認為,Foo不。好嗎?”;
我想得到輸出:
Foo喜歡酒吧嗎? 我不這么認為,富不。 好的?
與所有? 中間的文本用單引號(')代替。
我已經嘗試了以下代碼,但是可以嗎? 也將被Okay代替:
<?php
$str = "This is Agbeniga , he is a very good boy. He?s loved , but is he really is ? No , i don?t think so. but it?s working very good anyway , ya?ll all darling. Okay?";
$str = str_replace("?","0",$str);
//replace all question marks with zero
$divide=explode(" ",$str);
$str="";
foreach($divide as $div)
{
if(substr($div,0,1)===0)
{
$div=preg_replace("/0/", "?",$div);
}
$str .= ' ';
$str.=$div;
}
//split by spaces and replace words that have zero at the end with question mark
$str= preg_replace('/\b(?<!-)\d+(?!-)\b/',"?",$str);
//replace all stand alone zeros with question mark
$str = str_replace("0","'",$str);
//then replace the remaining zeros with single quote
echo $str;
?>
正則表達式可以檢查是否在問號的兩邊都放置了單詞邊界(“ \\ b”)
$str = "This is Agbeniga , he is a very good boy. He?s loved , but is he really is ? No , i don?t think so. but it?s working very good anyway , ya?ll all darling. Okay?";
$str= preg_replace('/\b\?\b/',"'",$str);
echo $str;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.