For importing articles by wpallimport
, I want them to be in the right category. In the csv file there is a column with several (sub) categories, separated by a space. Now i want to replace the space with >
by means of the str_replace
function, only there are article groups with the text "abcd & efgh", the space and &
space will also have to be replaced by >
sign. Is this possible?
The value groep[1]
is: PRINTER INKT & PAPIER
[str_replace(" ", ">", {groep[1]})]
It gives as result:
printer (group)
--inkt (subgroup)
---& (subgroup)
----papier (subgroup)
i need as result:
printer (group)
-inkt & papier (subgroup)
You can use regular expression functions, instead of plain str_replace
.
function preg_match_all
($pattern, $string, $matches)
will find all occurrences of the pattern in the string, and return them in the first element of the output $matches
array
$s = "PRINTER INKT & PAPIER ONE & TWO & THREE";
if (preg_match_all('#\S+(\s&\s\S+)*#', $s, $matches)) {
// $matches[0] - is an array, which contains all parts
print_r($matches[0]);
// to assemble them back into a string, using another delimiter, use implode:
$newstr = implode('>', $matches[0]);
print($newstr); // PRINTER>INKT & PAPIER>ONE & TWO & THREE
}
UPD.
If you insist on using str_replace
only, then you can apply it two times: the first - to replace all spaces to >
, then the second - to replace >&>
back to &
:
$s = "PRINTER INKT & PAPIER ONE & TWO & THREE";
$newstr = str_replace('>&>', ' & ', str_replace(' ', '>', $s));
print ($newstr); // PRINTER>INKT & PAPIER>ONE & TWO & THREE