PHP,在一个字符串中,如何在括号中将两个单词放在一起或多个旁边?

时间:2012-08-16 07:28:53

标签: php regex string uppercase

在字符串中,如何在括号中将两个或多个大写字母彼此相邻的单词放在一起。例如:

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

输出如下:(My) name is (John Ed), from (Canada)

5 个答案:

答案 0 :(得分: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)
?>

(John Ed)的事情应该有点棘手......

答案 1 :(得分: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).
?>

答案 2 :(得分:1)

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

答案 3 :(得分: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 properties

答案 4 :(得分: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)

试一试