Naeem Hussain
Naeem Hussain

Reputation: 21

How to Add Comma After Every Two Words in Php

I want to add Comma (,) After Two Words in the String below.

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

Result comes like below

Hello, Brother, I, am, Naeem, From, Php, College.

I want to get output Like below.

Hello Brother, I am, Naeem From, Php College.

Upvotes: 1

Views: 709

Answers (3)

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

The best approach here would be regex. Here is the code:

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

Breakdown:

  • 1st Capturing Group (\w+ \w+)
    • \w+ matches any word character (equal to [a-zA-Z0-9_])
    • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    •   matches the character literally (case sensitive)
    • \w+ matches any word character (equal to [a-zA-Z0-9_])
    • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
  • 2nd Capturing Group ( )
    •   matches the character literally (case sensitive)

Upvotes: 4

MAZux
MAZux

Reputation: 981

It's not a perfect solution, but you can try it:

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

Upvotes: 1

Joseph_J
Joseph_J

Reputation: 3669

There is probably a more elegant way of doing this, but here is my go at it:

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

Upvotes: 0

Related Questions