获取并替换包含的字符串中的单词?在字符串php正则表达式之间的单词

时间:2018-01-11 16:59:37

标签: php regex

我如何使用php regex来实现以下目标:

我有一个包含以下内容的字符串:

$ a =" Foo喜欢酒吧吗?我不这么认为,Foo没有。好吗?&#34 ;;

我希望获得输出:

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;
?>

1 个答案:

答案 0 :(得分:0)

正则表达式可以检查问号两边是否放置了单词边界(`\ b&#39;)

python manage.py runserver --http_timeout HTTP_TIMEOUT

demo