簡體   English   中英

PHP,在一個字符串中,如何在括號中將兩個單詞放在一起或多個旁邊?

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

在一個字符串中,如何在括號中將兩個或多個大寫字母彼此相鄰的單詞放在一起。 例:

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

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

第一個想法可能如下所示:

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

(約翰艾德)的事情應該有點棘手......

那這個呢:

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

如果要與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屬性的更多信息

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

試一試

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM