【问题标题】:replace all values in a string using preg_replace with callback使用带有回调的 preg_replace 替换字符串中的所有值
【发布时间】:2013-07-12 05:44:43
【问题描述】:

我不确定这是否可以用 preg_replace 完成,但这是我目前所拥有的

$string='
<div class="row">
  <section> [1] </section>
  <section> [2] </section>
  <section> [5] </section>
</div>';


function searchArray($myarray, $id) {
    foreach ($myarray as $item) {
        if ($item[$id] == $id)
            return $item['name'];
    }
    return false;
}

所以我需要通过 preg_replace 运行 $string,其中 [] 之间的每个 var 将对应于存储在多维数组中的实际 id。这就是函数 searchArray() 的用武之地。基本上运行字符串,将 [] 替换为实际 id 并打印字段名称。当我一次性提交表单时,所有这些都需要发生。

【问题讨论】:

    标签: php preg-replace


    【解决方案1】:

    用这样的东西代替 *preg_replace*...

    $arr = array('apple', 'pear', 'bananna', 'orange', 'grapefruit', 'pineapple');
    $string='
    <div class="row">
      <section> [1] </section>
      <section> [2] </section>
      <section> [5] </section>
    </div>';
    
    foreach($arr as $key => $value){
        $string = str_replace($key, $value, $string);
    }
    

    更新

    $arr = array(
        array('id'=>1, 'name'=>'matthew'),
        array('id'=>2, 'name'=>'william'),
        array('id'=>3, 'name'=>'john'),
        array('id'=>4, 'name'=>'george'),
        array('id'=>5, 'name'=>'henry'),
        array('id'=>6, 'name'=>'jason')
    );
    $string='
    <div class="row">
      <section> [1] </section>
      <section> [2] </section>
      <section> [4] </section>
        <section> [1] </section>
    </div>';
    foreach($arr as $key => $subArr){
        $string = str_replace("[".$subArr['id']."]", $subArr['name'], $string);
    }
    

    【讨论】:

    • 这行不通。是多维数组,每个[]都需要匹配实际的id,而不是替换成对应的name值
    • 那么您要替换的 ID 是什么?如果它是多维的,那么它将采用[][] ?? 的形式
    • 好的,我已经用更多代码更新了我的答案(如果我现在明白你的目标是什么)应该是你正在寻找的。​​span>
    猜你喜欢
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    相关资源
    最近更新 更多