文字列で、大文字を含む 2 つ以上の単語を括弧内に並べる方法。例:
$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)
?>
(ジョン・エド)とのことは少しトリッキーなはずです...
<?php
$str = "My name is John Ed, from Canada";
echo preg_replace('/([A-Z]\w*(\s+[A-Z]\w*)*)/', "($1)", $str);
?>
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 プロパティの詳細を参照してください
$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)
これを試してみてください