在一个字符串中,如何将两个或多个带有大写字母的单词放在括号中。例子:
$string = "My name is John Ed, from Canada";
输出是这样的:(My) name is (John Ed), from (Canada)
那这个呢:
<?php
$str = "My name is John Ed, from Canada and I Do Have Cookies.";
echo preg_replace("/([A-Z]{1}\w*(\s+[A-Z]{1}\w*)*)/", "($1)", $str); //(My) name is (John Ed), from (Canada) and (I Do Have Cookies).
?>
第一个想法可能如下所示:
<?php
$str = "My name is John Ed, from Canada";
echo preg_replace("/([A-Z]\\w*)/", "($1)", $str); //(My) name is (John) (Ed), from (Canada)
?>
(约翰·埃德)的事情应该有点棘手......
如果您想与 unicode 兼容,请使用以下命令:
$str = 'My name is John Ed, from Canada, Quebec, Saint-Laurent. My friend is Françoise';
echo preg_replace('/(\p{Lu}\pL*(?:[\s,-]+\p{Lu}\pL*)*)/', "($1)", $str);
输出:
(My) name is (John Ed), from (Canada, Quebec, Saint-Laurent). (My) friend is (Françoise)
解释:
( : start capture group 1
\p{Lu} : one letter uppercase
\pL* : 0 or more letters
(?: : start non capture group
[\s,-]+ : space, comma or dash one or more times
\p{Lu} : one letter, uppercase
\pL* : 0 or more letters
)* : 0 or more times non capture group
) : end of group 1
查看有关unicode 属性的更多信息
<?php
$str = "My name is John Ed, from Canada";
echo preg_replace('/([A-Z]\w*(\s+[A-Z]\w*)*)/', "($1)", $str);
?>
$str = "My name is John Ed, from Canada\n";
echo preg_replace("/([A-Z]\\w+( [A-Z]\\w+)*)/", "($1)", $str); //(My) name is (John Ed), from (Canada)
试试这个