【发布时间】:2014-06-20 21:11:27
【问题描述】:
我有一个类似的str:
'Test code {B}{X} we are implementing prototype {T} ,
using combinations of {U}{A} and {L/W}{F/K}.
我需要用相应的代码替换每一次出现的 {*},所以我的结果字符串是:
'Test code <img src="../B.jpg"><img src="../X.jpg">
we are implementing prototype <img src="../T.jpg">
,using combinations of <img src="../U.jpg">
<img src="../A.jpg"> and <img src="../LW.jpg">
<img src="../FK.jpg">.
我不想使用str_replace 并输入所有的组合,因为实际上有成千上万的组合。
$combinations = array("{B}", "{X}", "{W}{X},"{X/W}","{A/L}"..");等
所以我使用 preg_match_all 来查找字符串的所有匹配项。
function findMatches($start, $end, $str){
$matches = array();
$regex = "/$start([\/a-zA-Z0-9_]*)$end/";
preg_match_all($regex, $str, $matches);
return $matches[1];
}
回到我身边,
Array ( [0] => B [1] => X [2] => T [3] => U [4] => A [5] => L/W [6] => F/K )
问题是我不需要字母之间的“/”,我想我以后可以str_replace。
我的问题是如何使用匹配数组进行 preg_replace 并返回完全修改的字符串而不是数组?
【问题讨论】:
-
您使用了错误的工具来完成这项工作。你想要的是
preg_replace_callback。此外,完全不清楚您究竟在用findMatches做什么。 -
不知道这种语言。但是尝试
/\{(.)\}/并将其替换为与()内索引1 处的匹配组匹配的$1。我在here 测试过它有效。例如preg_replace('/\\{(.)\\}/', '$1', input_string),有 5 个匹配项。 -
试试
/\{([^}].*?)\}/以及匹配多个 {} 中的字母。