我的客户希望在惊叹号和问号之前留一个空格.为了确保始终正确完成,我在php中使用以下脚本.此脚本删除所有现有空格,然后在所有问号和感叹号之前放置一个不间断的空格:
$text = str_replace(' ?', '?', $text);
$text = str_replace('?', ' ?', $text);
$text = str_replace(' !', '!', $text);
$text = str_replace('!', ' !', $text);
return $text;
Run Code Online (Sandbox Code Playgroud)
一切正常,但我想知道Regex是否有更好的方法?
你可以用
$text = "No? Oh ? And ! and!";
$text = preg_replace('~\s*([?!])~', ' $1', $text);
echo $text;
Run Code Online (Sandbox Code Playgroud)
请参阅PHP演示
细节:
\s* - 0+空白符号([?!])- 第1组捕获?或!替换模式仅包含 对组1内容的反向引用以插入捕获的文本.
| 归档时间: |
|
| 查看次数: |
407 次 |
| 最近记录: |