0

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.

3 Answers 3

1
$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) . "'";
Sign up to request clarification or add additional context in comments.

8 Comments

Cool, thanks, your final edit worked. Can you please explain within the preg_replace, how have you done? I will accept this answer.
@sammry, this is matching (and then substituting with empty string) using RegEx, also known as Regular Expressions. Here's quickly googled-up something that should help you get the idea and learn how to use them: regexone.com/cheatsheet .
by the way, if I have to quote it like this, 'test',' 'new', 'hello'?
It matches " | (X)" pattern, just escaping | symbol, because unescaped means OR, exaping ( and ) because it is also symbols, .*? this means everything inside will be matched "non greedy". # this is start stop signs
Don't you think regex is a bit overkill? Some simple php methods could do this eg implode?
|
1

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

2 Comments

Thanks by the way, if I have to quote it like this, 'test',' 'new', 'hello'?
Go for the $arr[] = "'".$tt[0]."'";
0

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

?> `

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.