简体   繁体   中英

PHP, In a string, how to put two words beside each other or more in parentheses?

In a string, how to put two words or more which have capital letters beside each other in parentheses. example:

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

The output to be like this: (My) name is (John Ed), from (Canada)

A first idea could look like this:

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

The thing with (John Ed) should be a little tricky...

What about this:

<?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*(\s+[A-Z]\w*)*)/', "($1)", $str);
?>

If you want to be unicode compatible, use the following:

$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);

output:

(My) name is (John Ed), from (Canada, Quebec, Saint-Laurent). (My) friend is (Françoise)

explanation:

(           : 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

See more about unicode properties

$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)

Give this a try

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM