【问题标题】:Match and extract value from string pattern and replace with value corresponds to array key匹配并从字符串模式中提取值并替换为对应于数组键的值
【发布时间】:2018-01-24 06:43:24
【问题描述】:

我有 2 个数组,都包含人名和水果名。两个数组都是动态生成的。

$persons = array(0 =>'John', 1 => 'Alan', 2 => 'Ninja');

$fruits = array(0 =>'apple', 1 => 'mango', 2 => 'banana', 3 => 'kiwi');

还有一个字符串,我想根据模式提供的键对其执行替换。

$str = "[person1] eats [fruit1]";
$str2 = "These [fruit2] belongs to [person3] and his friends";

我希望我的输出像

$str = "John eats apple";
$str2 = "These mango belongs to Ninja and his friends";

我想搜索模式并从模式[person*][fruit*] 中获取* 的值,其中* 是动态生成的字符串。

编辑 1

我创建了一个函数

function replaceable_string($str, $elements, $pattern, $match="*"){
   foreach($elements as $index => $element){
     $index++;
     $new_pattern = str_replace($match, $index, $pattern);
     $str = str_replace($new_pattern, $element, $str);
   }
  return $str;
}

这样传递的值

$str = replaceable_string($str, $persons, '[person*]');
$str = replaceable_string($str, $fruits, '[fruit*]');
echo $str;

我不知道这有多高效。

或者有没有其他最好的方法来实现这一点?

【问题讨论】:

  • 您是否考虑过“合适的”模板系统

标签: php arrays string


【解决方案1】:

这是另一种方式。不确定是否更有效。

        $persons = array(0 =>'John', 1 => 'Alan', 2 => 'Ninja');

        $fruits = array(0 =>'apple', 1 => 'mango', 2 => 'banana', 3 => 'kiwi');

        $str = "[person1] eats [fruit1]";
        $str2 = "These [fruit2] belongs to [person3] and his friends";

        function replaceFromArr($str) {      
            global $persons, $fruits;
            $matches = [];
            preg_match_all("/\[([^\]]*)\]/", $str, $matches);
                //var_dump($matches[1]);

                foreach($matches[1] as $matched) {
                    // echo "$matched <br>";
                    $substr = substr($matched,0,6);
                    if($substr == "person") {
                        // extract index and fetch from persons array 
                        $index = substr($matched,6);
                        $replace = $persons[$index-1];

                        $str = str_replace("[$matched]",$replace,$str);                    
                    }
                    else {
                        // extract index and fetch from fruits array 
                        $index = substr($matched,5);
                        $replace = $fruits[$index-1];

                        $str = str_replace("[$matched]",$replace,$str);                   

                    }
                }                
            return $str;
        }


        $newStr = replaceFromArr($str);
        echo "--- $newStr ---<br>";

        $newStr = replaceFromArr($str2);
        echo "--- $newStr ---<br>"; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    相关资源
    最近更新 更多