如何在Php中每两个单词后添加逗号

时间:2018-03-25 06:15:20

标签: php regex string

我想在下面的字符串中添加两个单词之后的逗号(,)。

$mystring = "Hello Brother I am Naeem From Php College.";
$output = str_replace('', ', ', $mystring);
echo $output;

结果如下所示

你好,兄弟,我,我,Naeem,From,Php,学院。

我想得到如下所示的输出。

你好兄弟,我是,Naeem From,Php College。

3 个答案:

答案 0 :(得分:4)

这里最好的方法是正则表达式。这是代码:

$str = 'Hello Brother I am Naeem From Php College.';
$result = preg_replace('/(\w+ \w+)( )/', '$1, ', $str);
echo $result; // output: Hello Brother, I am, Naeem From, Php College.

<强>故障:

  • 第一捕获小组(\w+ \w+)
    • \w+匹配任何字词(等于[a-zA-Z0-9_]
    • +量词 - 在一次和无限次之间匹配,尽可能多次,根据需要回馈(贪婪)
    • 字面匹配字符(区分大小写)
    • \w+匹配任何字词(等于[a-zA-Z0-9_]
    • +量词 - 在一次和无限次之间匹配,尽可能多次,根据需要回馈(贪婪)
  • 第二捕获小组( )
    • 字面匹配字符(区分大小写)

答案 1 :(得分:1)

这不是一个完美的解决方案,但你可以尝试一下:

$wordsArray = explode(' ', $mystring);
$returnedStr = '';
foreach ($wordsArray as $index => $word) {
    if($index % 2 == 1) {
        $returnedStr .= $word .', ';
        continue;
    }
    $returnedStr .= $word . ' ';
}

答案 2 :(得分:0)

这可能是一种更优雅的方式,但这是我的理由:

$mystring = "Hello Brother I am Naeem From Php College.";

$array = explode(' ', $mystring);

$output = $array[0] . ' ';

$switch = FALSE;
for($i = 1; $i < count($array); $i++){

if($switch === FALSE){

$output = $output . ' ' . $array[$i];

$switch = TRUE;

} else {

 $output = $output . ', ' . $array[$i];

 $switch = FALSE;

}

echo $output;  // Hello Brother, I am, Naeem From, Php College.
相关问题