PHP preg_replace_callback 的正则表达式
正则表达式不是我的菜。 :(
我有一个可能包含多个子字符串的字符串,例如:
[var1="111" var2="222" var3="222" var4="444"]
我基本上需要将每个出现的地方替换为获取每个变量的函数的结果。
$string = '[var1="111" var2="222" var3="333" var4="444"]';
$regex = 'var1="(.*)" var2="(.*)" var3="(.*)" var4="(.*)"';
function doit($matches){
return "<strong>".implode(", ", $matches) ."</strong>";
}
echo preg_replace_callback($regex,'doit',$string);
我期望 111, 222, 333, 444.
但我没有感受到任何帮助!
编辑:一些澄清..
我只是为了这个问题而简化
“vars”实际上并没有。是 称为“var1”,“var2”更像 [recID =“22”模板=“theName” option="some value", type="list"]
回调会更多 复杂然后我简单 内爆...我会使用“id”和 连接到数据库,获取 记录并将它们插入到 模板...因此需要 回电...
匹配的值可能几乎 任何东西,而不仅仅是数字。
Regular expressions is just not my thing. :(
I have a string that may contain multiple sub strings such as:
[var1="111" var2="222" var3="222" var4="444"]
I basically need to replace each occurrence with the results of a function that gets each variable.
$string = '[var1="111" var2="222" var3="333" var4="444"]';
$regex = 'var1="(.*)" var2="(.*)" var3="(.*)" var4="(.*)"';
function doit($matches){
return "<strong>".implode(", ", $matches) ."</strong>";
}
echo preg_replace_callback($regex,'doit',$string);
I’m expecting 111, 222, 333, 444.
But I’m not feeling the love. Any help would be appreciated!
Edit: some clarification..
I was simplifying for the sake of the question.
the "vars" will not really be
called "var1", "var2" more like
[recID="22" template="theName"
option="some value", type="list"]the call back would be more
complicated then my simple
implode... I would use "id" and
connect to a database, get the
records and insert them into the
template... Hence the need for the
call back...matched values could be almost
anything, not just numbers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会分两步完成:
这是一个示例:
通过这个,您甚至可以检测语法错误。
这不是一个完美的解决方案,因为逐字符读取输入并根据它们所在的上下文确定标记会更有效。
I would do it in two step:
Here’s an example:
With this you can even detect syntax errors.
It’s not a perfect solution as it would be more efficient to read the input character by character and determine the tokens depending on the contexts they are found in.
另一个答案可能是更好的解决方案,但以下是如何使用 preg_replace_callback 来做到这一点:
The other answer may be a better solution, but here is how you could do it with preg_replace_callback: