我想创建自己的短代码
在文中我可以把短代码例如:
The people are very nice,[gal~route~100~100],the people are very
nice,[ga2l~route2~150~150]
在这个表达式中你可以看到[]标签中的短代码,我希望显示没有这个短代码的文本并将其替换为库(使用PHP include并从短代码中读取路径库)
我认为使用这种方法,你可以看到,但它们都不适合我,但是这里的人可以告诉我一些事情或给我任何可以帮助我的想法
- <?PHP
- $art_sh_exp=explode("][",html_entity_decode($articulos[descripcion],ENT_QUOTES));
- for ($i=0;$i<count($art_sh_exp);$i++) {
- $a=array("[","]"); $b=array("","");
- $exp=explode("~",str_replace ($a,$b,$art_sh_exp[$i]));
- for ($x=0;$x<count($exp);$x++) { print
- "".$exp[1]."-".$exp[2]."-".$exp[3]."-<br>"; }
- } ?>
谢谢
我建议你使用正则表达式来查找短代码模式的所有出现.
它使用preg_match_all(文档here)查找所有出现的内容,然后使用简单的str_replace(文档here)将已转换的短代码放回字符串中
此代码中包含的正则表达式只是尝试匹配0到括号[和]之间的字符的无限次出现
- $string = "The people are very nice,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,ga2l - route2 - 150 - 150
通过分两个阶段解决问题
>查找所有事件
>用新值替换它们
开发和调试更简单.如果您想在一定程度上更改您的短代码如何转换为URL或其他内容,它也会更容易.
编辑:按照杰克的建议,使用preg_replace_callback可以做到更简单.看他的答案.