【问题标题】:(PHP) Replacing a string with an array value(PHP) 用数组值替换字符串
【发布时间】:2016-06-22 06:15:27
【问题描述】:

我有一个正则表达式,可以在两个方括号之间找到文本:

preg_match_all("/(?<=\[).+?(?=\])/", $body, $matches);

我需要从一个名为 row 的数组中获取与正则表达式匹配的键的值,并将其替换为 $body 字符串。

例如,

foreach ($matches[0] as $array_key) {
    row->$array_key;
    //The value at the specific key, but I need to take this value and put it back in the spot where its key was found in the body string

}

【问题讨论】:

  • 任何示例字符串和预期输出?这个问题听起来不清楚。看起来你正在寻找preg_repace
  • 还有代码吗?
  • row-&gt;$array_key; 看起来您正在使用对象,而不是数组。显示 $bodyrow 的示例输入内容
  • 有些人一问就逃了。看,这不是一个传统的论坛,它是 StackOverflow。

标签: php arrays regex


【解决方案1】:

试试这个:

$body = '[testtext][othertext]';
preg_match_all("/(?<=\[).+?(?=\])/", $body, $matches);

foreach($matches[0] as $key => $value)
{
    $values[] = $value;
}
print_r($values);

结果是:

Array ( [0] => testtext [1] => othertext )

这是你想要的吗?

【讨论】:

    【解决方案2】:

    这对我有用

     <pre>
        <?php 
         $b = "Name: some sample text [] and some other [] and the thired one [] and 4 [] putting it on end[] and some thing after";
         preg_match_all("/(?<=\[).+?(?=\])/", $b, $m);
    
         $str = substr($b, 0,strpos($b, '[')+1);
    
         $row= array("val1","val2","val3","val4","val5");
    
         foreach($row as $k => $value) {
    
            $afterstr =  (  $k <=  count($m[0])-1 ) ?  $m[0][$k] : ""; // because the last ']' is not in $m array so we have to handle that
            $str .= $value . $afterstr ;
        }
    
        $str .= strrchr($b,']'); // appending after the last ']' text
        var_dump($str);
    

    string(135) "名称:一些示例文本 [val1] 和一些其他 [val2] 以及第三个 [val3] 和 4 [val4] 将其放在 end[val5] 和后面的一些东西强>

    【讨论】:

      猜你喜欢
      • 2014-02-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      • 2011-06-26
      • 1970-01-01
      • 2014-03-27
      • 1970-01-01
      • 2014-03-21
      相关资源
      最近更新 更多