有时字符串有单字和双字,它适用于单个单词,但不适用于空格的双重
$_POST['descricao'] = "UNITED STATES test";
$_POST['descricao'] = preg_replace("/\b([A-Z]{2,})\b/", "<b>$1</b>", $_POST['descricao']);
输出:<b>UNITED</b> <b>STATES</b> teste
每次我发送表单时,它都会像<b><b>UNITED</b></b> <b><b>STATES</b></b> test
对于字符串$str = "UNITED STATES test"
,它应输出:<b>UNITED STATES test</b> instead of <b>UNITED</b> <b>STATES</b> test
答案 0 :(得分:1)
[A-Z]
字符类不包含任何空格。如果需要,请添加空格:
- 添加了\s
$_POST['descricao'] = preg_replace("/\b([A-Z\s]{2,})\b/", "<b>$1</b>", $_POST['descricao']);
但如果你最多只需要两个单词,那么这可能比你需要的更多:
- 添加了:(\s[A-Z]{2,})?
$_POST['descricao'] = preg_replace("/\b([A-Z]{2,}(\s[A-Z]{2,})?)\b/", "<b>$1</b>", $_POST['descricao']);
双<b><b>
... </b></b>
如果您真的必须在一行代码中完成所有操作,可能有一种方法可以使用外观和前瞻。但是,我会像这样做一个快速而脏的preg_replace清理:
$_POST['descricao'] = preg_replace('/<(\/)?b><(?:\/)?b>/', "<$1b>", $_POST['descricao']);
^^将删除任何重复