正则表达式替换PHP中的自定义“变量”

时间:2017-07-12 09:32:00

标签: php regex

有没有人知道如何使用preg_replace实现以下的正则表达式?

我有一个如下字符串:

$string = "Best event in town is: [LOC=LONDON]Party London[/LOC] (more text...) [LOC=PARIS]Paris Party[/LOC] Check it out!";

我有一个位置:

$location = "LONDON"

现在我需要用[LOC = *]和[/ LOC]之间的文本替换当前位置$ location的自定义文本,并删除所有与当前位置不匹配的文本。不应删除方括号之间的文本。

在上面的示例中,结果应如下所示:

  Best event in town is: Party London (more text...) Check it out!

您是否知道如何使用preg_match进行操作,或者您知道其他任何有效方法吗?

提前致谢! 托拜厄斯

3 个答案:

答案 0 :(得分:1)

你可以试试这个:

\[(?=LOC=LONDON)[^\]]*?\]([^[]*)\[\/LOC\]|\[LOC[^]]*\][^\[]*\[\/LOC\]

并替换为:

\1

Regex Demo

示例来源(Run Here):

$location="LONDON";
$re = '/\[(?=LOC='.$location.')[^\]]*?\]([^[]*)\[\/LOC\]|\[LOC[^]]*\][^\[]*\[\/LOC\]/';
$str = 'Best event in town is: [LOC=LONDON]Party London[/LOC] (more text...) [LOC=PARIS]Paris Party[/LOC] Check it out! [LOC=DHAKA]dHAKA Party[/LOC] Check it out! ';
$subst = '\\1';
$result = preg_replace($re, $subst, $str);
echo $result;

答案 1 :(得分:1)

最通用的解决方案使用preg_replace_callback()

regex

[LOC][/LOC]匹配一个LOC块并捕获\[ # matches the "[" character (unescaped, it is a meta-character) LOC= # matches the string "LOC=" (there is nothing special about it) ( # start of the first capturing group (doesn't match anything) [^\]]* # matches any character except `]`, zero or more times (`*`) ) # end of the first capturing group (doesn't match anything) ] # matches the "]" character itself (it doesn't need to be # escaped when used outside of a character class) ( # start of the second capturing group .*? # matches any character, any number of times, not greedy (`?`) ) # end of the second capturing group \[/LOC\] # matches the string "[/LOC]" 的值和块的内容:

preg_replace_callback()

当找到匹配项时,array使用一个类型为0的参数调用给定的回调函数,该参数在索引regex处包含与{{1}匹配的字符串部分}(fe [LOC=LONDON]Party London[/LOC])和以1开头的数字索引,与相应的捕获组匹配的字符串片段(如果有)。

对于输入字符串,当第一次调用回调时,print_r($matches)如下所示:

Array
(
    [0] => [LOC=LONDON]Party London[/LOC]
    [1] => LONDON
    [2] => Party London
)

回调的代码不需要太多解释。如果$matches[1][LOC=]之间的字符串与$location相同,则将匹配的字符串替换为$matches[2][LOC=...]之间的字符串和[/LOC]),否则用空字符串替换它(删除[LOC][/LOC]块及其内容)。

答案 2 :(得分:1)

function stringInject(str, arr) {
    if (typeof str !== 'string' || !(arr instanceof Array)) {
        return false;
    }

    return str.replace(/({\d})/g, function(i) {
        return arr[i.replace(/{/, '').replace(/}/, '')];
    });
}

<强>用法

var oldString = "Best party in town is in {0}. Not in {1}";
var newString = stringInject(oldString, ["London", "Paris"]);

// Best party in town is in London. Not in Paris.

<强> GitHub的

https://github.com/tjcafferkey/stringinject

<强> NPM

https://www.npmjs.com/package/stringinject