如何在Php中每两个单词后添加逗号
我想在下面字符串中的两个单词后添加逗号(,)如何在Php中每两个单词后添加逗号,php,regex,string,Php,Regex,String,我想在下面字符串中的两个单词后添加逗号(,) $mystring = "Hello Brother I am Naeem From Php College."; $output = str_replace('', ', ', $mystring); echo $output; 结果如下所示 你好,兄弟,我是,Naeem,来自Php大学 我希望获得如下输出。 你好,兄弟,我是,来自Php学院的Naeem。也许有一种更优雅的方法可以做到这一点,但我的做法是: $mystring = "Hello
$mystring = "Hello Brother I am Naeem From Php College.";
$output = str_replace('', ', ', $mystring);
echo $output;
结果如下所示
你好,兄弟,我是,Naeem,来自Php大学
我希望获得如下输出。
你好,兄弟,我是,来自Php学院的Naeem。也许有一种更优雅的方法可以做到这一点,但我的做法是:
$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.
$mystring=“你好,兄弟,我是Php学院的Naeem。”;
$array=explode(“”,$mystring);
$output=$array[0]。';
$switch=FALSE;
对于($i=1;$i
也许有一种更优雅的方法可以做到这一点,但我的做法是:
$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.
$mystring=“你好,兄弟,我是Php学院的Naeem。”;
$array=explode(“”,$mystring);
$output=$array[0]。';
$switch=FALSE;
对于($i=1;$i
这不是一个完美的解决方案,但您可以尝试:
$wordsArray = explode(' ', $mystring);
$returnedStr = '';
foreach ($wordsArray as $index => $word) {
if($index % 2 == 1) {
$returnedStr .= $word .', ';
continue;
}
$returnedStr .= $word . ' ';
}
这不是一个完美的解决方案,但您可以尝试:
$wordsArray = explode(' ', $mystring);
$returnedStr = '';
foreach ($wordsArray as $index => $word) {
if($index % 2 == 1) {
$returnedStr .= $word .', ';
continue;
}
$returnedStr .= $word . ' ';
}
这里最好的方法是正则表达式。下面是代码:
$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\]
量词-在一次和无限次之间进行匹配,尽可能多地匹配,根据需要返回(贪婪)+
- 第二捕获组
()
逐字匹配字符
(区分大小写)
- 这里最好的方法是正则表达式。下面是代码:
$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\]
量词-在一次和无限次之间进行匹配,尽可能多地匹配,根据需要返回(贪婪)+
- 第二捕获组
()
逐字匹配字符
(区分大小写)