请返回匹配值请问该怎么做?如何使用preg_replace()
<?php
$string = '<inc="file.php">';
return preg_replace('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#',include("$1"),$string);
?>
输出返回$ 1
我需要返回file.php包括
请返回匹配值请问该怎么做?如何使用preg_replace()
<?php
$string = '<inc="file.php">';
return preg_replace('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#',include("$1"),$string);
?>
输出返回$ 1
我需要返回file.php包括
我觉得应该是
return preg_replace('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#','include("'.$1.'")',$string);
第二个参数应该是一个字符串。
是的,谢谢你的好工作 – user1179177 2012-04-28 20:20:45
如果你有PHP 5.3或更高版本:
<?php
$string = '<inc="file.php">';
return preg_replace_callback('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#', function($matches) {
return include $matches[1];
}, $string);
?>
是的,这是很好的谢谢 – user1179177 2012-04-28 20:22:55
我不完全相信您正在尝试执行此操作,但请尝试在preg_replace上使用preg_match
。
它收集的匹配到一个数组,如果你使用它像图所示:
preg_match('#<inc\s*="\s*([a-zA-Z0-9\_]+)\">#', $string, $matches);
然后比赛被存储在$matches
阵列英寸然后,您可以使用foreach
对它们进行循环。
他为什么要这样做:** TLDR; * |不想做正则表达式2x | *** ...完整的例子:想象一下,你有一些数据和一个数据项的一个属性是包含额外的东西,不属于你的特定环境,但你不想扔掉它 - 它只属于你的上下文中的其他地方 - 如此低效地你可以1.搜索它,然后2.搜索并替换它 - 你会搜索两次(2次),这是不必要的,这就是为什么有人想要这个:-)旁注:如果你认为OP想要的东西与他/她所要求的不同 - 请先评论一下;) – 2017-04-19 21:31:11
先尝试'sscanf'。 – hakre 2012-04-29 16:26:28
@hakre这究竟会有帮助吗?我不认为它取代...无论如何,我想知道为什么有人不喜欢这个问题,因为它没有标记? – 2017-04-19 21:21:19