简体   繁体   English

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

[英]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) 输出如下:( (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: 如果要与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);

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 查看有关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)

Give this a try 试一试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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