sammry
sammry

Reputation: 412

PHP Explode and Implode a String

I am half way done and struck at imploding on the output.

I have a string as

$text = "test | (3), new | (1), hello | (5)";
$text = explode(",", $text);
foreach ($text as $t){
    $tt = explode(" | ", $t);
    print_r($tt[0]);
}

When I print the above array, it gives me test new hello as needed, now, I need to put a comma like this test, new, hello

I searched and could not achieve hence posting here to get help.

Upvotes: 0

Views: 2042

Answers (3)

Ashish Butola
Ashish Butola

Reputation: 15

1- Implode is a function in php where you can convert a array into string Ex-

$arr = array('Hello','World!','Beautiful','Day!');

echo implode(" ",$arr);

?>

2- Explode is a function in php where you can convert a string into array

Ex-

$str = "Hello world. It's a beautiful day.";

print_r (explode(" ",$str));

?> `

Upvotes: 0

jskidie
jskidie

Reputation: 154

$text = "test | (3), new | (1), hello | (5)";
echo preg_replace('# \| \(.*?\)#', '', $text);

EDIT: to reach result like 'test',' 'new', 'hello'

$text = "test | (3), new | (1), hello | (5)";
$text = preg_replace('# \| \(.*?\)#', '', $text);
echo "'" . preg_replace('#,#', "', '", $text) . "'";

Upvotes: 1

sitilge
sitilge

Reputation: 3737

Yes, you can push them to array and implode later on

$text = "test | (3), new | (1), hello | (5)";

$text = explode(",", $text);

$arr = array();

foreach ($text as $t){
    $tt = explode(" | ", $t);
    $arr[] = $tt[0];
}

echo implode(", ", $arr);

Upvotes: 1

Related Questions