如何将 str_replace 的值拆分为 wpallimport 以使用类别
How to split a value by str_replace into wpallimport for using category
对于 wpallimport
的导入文章,我希望它们属于正确的类别。在 csv 文件中有一列包含多个(子)类别,由 space 分隔。现在我想通过 str_replace
函数将 space 替换为 >
,只有带有文本 "abcd & efgh"、space 和 &
space 也必须替换为 >
符号。这可能吗?
值groep[1]
是:PRINTER INKT & PAPIER
[str_replace(" ", ">", {groep[1]})]
结果为:
printer (group)
--inkt (subgroup)
---& (subgroup)
----papier (subgroup)
我需要作为结果:
printer (group)
-inkt & papier (subgroup)
您可以使用正则表达式函数,而不是普通的 str_replace
。
function preg_match_all
($pattern, $string, $matches)
将在字符串中找到所有出现的模式,并且 return 它们在输出的第一个元素中 $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.
如果您坚持只使用 str_replace
,那么您可以应用两次:第一次 - 将所有空格替换为 >
,然后第二次 - 将 >&>
替换回 &
:
$s = "PRINTER INKT & PAPIER ONE & TWO & THREE";
$newstr = str_replace('>&>', ' & ', str_replace(' ', '>', $s));
print ($newstr); // PRINTER>INKT & PAPIER>ONE & TWO & THREE
对于 wpallimport
的导入文章,我希望它们属于正确的类别。在 csv 文件中有一列包含多个(子)类别,由 space 分隔。现在我想通过 str_replace
函数将 space 替换为 >
,只有带有文本 "abcd & efgh"、space 和 &
space 也必须替换为 >
符号。这可能吗?
值groep[1]
是:PRINTER INKT & PAPIER
[str_replace(" ", ">", {groep[1]})]
结果为:
printer (group)
--inkt (subgroup)
---& (subgroup)
----papier (subgroup)
我需要作为结果:
printer (group)
-inkt & papier (subgroup)
您可以使用正则表达式函数,而不是普通的 str_replace
。
function preg_match_all
($pattern, $string, $matches)
将在字符串中找到所有出现的模式,并且 return 它们在输出的第一个元素中 $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.
如果您坚持只使用 str_replace
,那么您可以应用两次:第一次 - 将所有空格替换为 >
,然后第二次 - 将 >&>
替换回 &
:
$s = "PRINTER INKT & PAPIER ONE & TWO & THREE";
$newstr = str_replace('>&>', ' & ', str_replace(' ', '>', $s));
print ($newstr); // PRINTER>INKT & PAPIER>ONE & TWO & THREE