解析字符串 php 并替换子字符串 [英] Parse through a string php and replace substrings

查看:70
本文介绍了解析字符串 php 并替换子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,在 PHP 中,该字符串出现了 %%abc%%(some substring)%%xyz%%

I have a string, in PHP and the string has occurrences of the pattern %%abc%%(some substring)%%xyz%%

在主字符串中多次出现此类子字符串.这些出现中的每一个都需要用数组中的字符串替换array('substring1','substring2','substring3','substring4') 取决于 function() 的响应,它返回 1 到 4 之间的整数.

There are multiple occurrences of such substrings within the master string. Each of these occurrences need to be replaced with a string from within an array array('substring1','substring2','substring3','substring4') depending upon the response of a function() which returns back a integer between 1 to 4.

我无法找到一种有效的方法来做到这一点.

I am not able to figure out an efficient way to do this.

推荐答案

这种情况需要 preg_replace_callback:

This is a situation that calls for preg_replace_callback:

// Assume this already exists
function mapSubstringToInteger($str) {
    return (strlen($str) % 4) + 1;
}

// So you can now write this:
$pattern = '/%%abc%%(.*?)%%xyz%%/';
$replacements = array('r1', 'r2', 'r3', 'r4');
$callback = function($matches) use ($replacements) {
    return $replacements[mapSubstringToInteger($matches[1])];
};

preg_replace_callback($pattern, $callback, $input);

这篇关于解析字符串 php 并替换子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆