【问题标题】:Preg_replace all patterns in a stringPreg_replace 字符串中的所有模式
【发布时间】: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 个匹配项。
  • 试试 /\{([^}].*?)\}/ 以及匹配多个 {} 中的字母。

标签: php regex string


【解决方案1】:

我建议使用preg_replace_callback() 来实现这一点。然后,您可以使用str_replace() 方法替换回调函数返回的匹配项中的正斜杠/

$text = <<<DATA
Test code {B}{X} we are implementing prototype {T} ,
 using combinations of {U}{A} and {L/W}{F/K}. 
DATA;

$text = preg_replace_callback('~{([^}]*)}~', 
      function($m) {
         return '<img src="../' . str_replace('/', '', $m[1]) . '.jpg">';
      }, $text);

echo $text;

Working Demo

【讨论】:

  • 啊,这很好用,谢谢不知道 preg_replace_callback
【解决方案2】:

这会让你走到一半,但你仍然需要一个替换来删除/

<?php
$input='Test code {B}{X} we are implementing prototype {T} ,
 using combinations of {U}{A} and {L/W}{F/K}.';

$output = preg_replace("/{([^}]*)}/", '<img src="../' . '\\1' . '.jpg">', $input);
echo $output."\n";
?>

输出:

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="../L/W.jpg"><img src="../F/K.jpg">.

【讨论】:

  • 如何将 {L/W}{F/K} 中的“/”替换为 LW.jpg 或 FK.jpg?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-10
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多