对于通过wpallimport导入文章,我希望它们属于正确的类别。在csv文件中有一个列,列有几个(子)类别,用空格分隔。现在我想用>函数来代替str_replace空间,只有文本"abcd & efgh“的项目组,空间和&空间也将被>符号所取代。这个是可能的吗?
值groep[1]是:PRINTER INKT & PAPIER
[str_replace(" ", ">", {groep[1]})]
其结果是:
printer (group)
--inkt (subgroup)
---& (subgroup)
----papier (subgroup)因此,我需要:
printer (group)
-inkt & papier (subgroup)发布于 2019-09-11 13:14:41
您可以使用正则表达式函数,而不是普通的str_replace。
函数preg_match_all($pattern, $string, $matches)将在字符串中查找所有出现的模式,并在输出$matches数组的第一个元素中返回它们。
$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.如果您坚持只使用str_replace,那么您可以使用它两次:第一次将所有空格替换为>,第二次将>&>替换回&。
$s = "PRINTER INKT & PAPIER ONE & TWO & THREE";
$newstr = str_replace('>&>', ' & ', str_replace(' ', '>', $s));
print ($newstr); // PRINTER>INKT & PAPIER>ONE & TWO & THREEhttps://stackoverflow.com/questions/57888857
复制相似问题