2

文字列で、大文字を含む 2 つ以上の単語を括弧内に並べる方法。例:

   $string = "My name is John Ed, from Canada";

出力は次のようになります。(My) name is (John Ed), from (Canada)

4

5 に答える 5

3

これはどうですか:

<?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).
?>
于 2012-08-16T07:53:12.193 に答える
3

最初のアイデアは次のようになります。

<?php
    $str = "My name is John Ed, from Canada";
    echo preg_replace("/([A-Z]\\w*)/", "($1)", $str); //(My) name is (John) (Ed), from (Canada)
?>

(ジョン・エド)とのことは少しトリッキーなはずです...

于 2012-08-16T07:40:50.433 に答える
1
<?php
  $str = "My name is John Ed, from Canada";
  echo preg_replace('/([A-Z]\w*(\s+[A-Z]\w*)*)/', "($1)", $str);
?>
于 2012-08-16T07:55:18.733 に答える
1

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 プロパティの詳細を参照してください

于 2012-08-16T11:30:58.463 に答える
0
$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)

これを試してみてください

于 2012-08-16T08:01:26.707 に答える