I am having trouble to separate the text.
This is the scenario:
$check = "Apple|Orange|Animal|Dog|Grape";
Suppose by using explode i could separate the word with “|”, but because the value i retrieved “Animal|Dog” should be a word so in this case, what would be the solution?? I could not use
limit as well because the position or number of text could be different.
The only way to distinctly separate the text is the Animal keyword. Is there any function in php that similar to mysql LIKE syntax?
If Case 2
$check = "Apple|Orange|Animal:Dog|Cat|Grape";
OR
$check = "Apple|Orange|Animal:Fish|Bird|Grape";
where the name of animal could be vary.
Output
"Apple|Orange|Animal:Dog,Cat|Grape" or "Apple|Orange|Animal:Fish,Bird|Grape"
Thanks.
If all you want to do is replace “Animal|” with “Animal:” then you can do a simple
str_replace:Is that what you meant?
EDIT, FOR CASE 2:
I assume you have a string like
"Apple|Orange|Animal:Dog|Cat|Grape", which has the category followed by 2 members of the category. From what you’ve said, you want to transform this string into"Apple|Orange|Animal:Dog,Cat|Grape"with a comma separating the two group members instead of a pipe. This is more complicated than the first case – the category name could vary, and you can’t do a simplestr_replacestarting with the colon because the first member of the group could vary as well. For this case, you’ll need to use a regular expression to match and replace the pattern of the string. Here’s the code:DEMO
Let me explain what this does, in case you’re not familiar with regular expressions. The first argument of the
preg_replacefunction,"#(Animal:\w+)\|#", tells PHP to look for all substrings of$checkthat begin with the text “Animal” followed by a colon, then a string of words with one or more character, and end with a pipe. This will look for the category name as well as the first member of that category in your string. The second argument,":$1,", tells PHP to change the first pipe after this pattern into a comma. If you have a different category name, simply change the pattern you pass as the first argument to thepreg_replacefunction:Let me know if this is hard to follow!