我建议你使用正则表达式来查找短代码模式的所有出现.
它使用preg_match_all(文档here)查找所有出现的内容,然后使用简单的str_replace(文档here)将已转换的短代码放回字符串中
此代码中包含的正则表达式只是尝试匹配0到括号[和]之间的字符的无限次出现
$string = "The people are very nice , [gal~route~100~100] , the people are very nice , [ga2l~route2~150~150]";
$regex = "/\[(.*?)\]/";
preg_match_all($regex, $string, $matches);
for($i = 0; $i < count($matches[1]); $i++)
{
$match = $matches[1][$i];
$array = explode('~', $match);
$newValue = $array[0] . " - " . $array[1] . " - " . $array[2] . " - " . $array[3];
$string = str_replace($matches[0][$i], $newValue, $string);
}
结果字符串现在是
The people are very nice , gal - route - 100 - 100 , the people are very nice , ga2l - route2 - 150 - 150
通过分两个阶段解决问题
>查找所有事件
>用新值替换它们
开发和调试更简单.如果您想在一定程度上更改您的短代码如何转换为URL或其他内容,它也会更容易.
编辑:按照杰克的建议,使用preg_replace_callback可以做到更简单.看他的答案.