我想创建自己的短代码
在文中我可以把短代码例如:
人很好,[gal~路线~100~100],人们都很好,[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>"; }
} ?>
Run Code Online (Sandbox Code Playgroud)
谢谢
我建议你使用正则表达式来查找短代码模式的所有出现.
它使用preg_match_all(此处的文档)查找所有事件,然后简单str_replace(此处为文档)将已转换的短代码放回字符串中
包含在该代码中的正则表达式简单地尝试匹配0至括号之间的字符的无限OCCURENCES [和]
$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);
}
Run Code Online (Sandbox Code Playgroud)
结果字符串现在是
The people are very nice , gal - route - 100 - 100 , the people are very nice , ga2l - route2 - 150 - 150
Run Code Online (Sandbox Code Playgroud)
通过分两个阶段解决问题
开发和调试更简单.如果您想在一定程度上更改您的短代码如何转换为URL或其他内容,它也会更容易.
编辑:正如杰克所建议的那样,使用preg_replace_callback可以更简单地做到这一点.看他的回答.
| 归档时间: |
|
| 查看次数: |
12173 次 |
| 最近记录: |