我想在我的 PHP 代码中删除我的段落中的几个问号。
例如:
$str = " Hi ?How? are you? Hope you are good. ";
输出应该是:
$str = " Hi How are you? Hope you are good. ";
所以段落中的单词有开始和结束字符“?” (问号),则应删除两个问号。请建议。请提出实现这一目标的最佳方法。
试试这个:
$str = " Hi ?How? are you? Hope you are good. ";
$newstr = preg_replace('/\?([a-z0-9]{1,}?)\?/si','$1',$str);
echo $newstr;
尝试以下操作:
$str = preg_replace('/\\?(\\w+)\\?','$1',$str);
这将匹配由 . 包围的任何“单词” ?
。匹配“\w
任何单词字符(字母、数字、下划线)”。意思是“+
一个或多个”。如果您还想匹配??
和删除它们,可以将其替换为*
.
$string = " Hi ?How? are you? Hope you are good. ";
$pattern = "/\?(\w+)\?/";
$replacement = '${1}';
echo preg_replace($pattern, $replacement, $string);
$str = " Hi ?How? are you? Hope you are good. ";
echo preg_replace("/\?(\w+)\?/", "$1", $str);
最简单的正则表达式将是\?([^\?\s]+)\?
您的单词在第一组中的位置。你可能不得不像 php 需要它一样逃避它。