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

如果您想与 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 回答
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 回答
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 回答