php 中使用正则表达式处理的模板、变量
Templates, variables processing with regexp in php
我有多行字符串,其中包含一些变量,例如 $Item_#1_Value$
、$Item_#2_Value$
等。我想用实际值替换(不区分大小写)所有这些实例,这不是 str_ireplace()
.
的问题
问题是我还需要删除所有可能(或可能不)与这些变量相邻的空格。其他空间,不与变量相邻,我不需要触摸。
例如:
如果 $item_#1_Value$
是 1234
,那么字符串:
ABC$item_#1_Value$QWERT
、ABC $ITEM_#1_VALUE$ QWERT
、ABC $item_#1_Value$ QWERT
都需要替换成ABC1234QWERT
.
我明白应该使用 preg_replace(...)
而不是 str_ireplace(...)
,但我不知道应该使用哪种正则表达式模式。
使用正则表达式的一种方法是将您的标签与可选的周围多个空格相匹配:
\s*$item_#1_Value$\s*
PHP代码
<?php
$strings[] = 'ABC$item_#1_Value$QWERT';
$strings[] = 'ABC $ITEM_#1_VALUE$ QWERT';
$strings[] = 'ABC $item_#1_Value$ QWERT';
foreach ($strings as $string) {
$string = preg_replace('/\s*$item_#1_Value$\s*/i', "1234", $string);
echo $string.PHP_EOL;
}
结果
ABC1234QWERT
ABC1234QWERT
ABC1234QWERT
我有多行字符串,其中包含一些变量,例如 $Item_#1_Value$
、$Item_#2_Value$
等。我想用实际值替换(不区分大小写)所有这些实例,这不是 str_ireplace()
.
问题是我还需要删除所有可能(或可能不)与这些变量相邻的空格。其他空间,不与变量相邻,我不需要触摸。
例如:
如果 $item_#1_Value$
是 1234
,那么字符串:
ABC$item_#1_Value$QWERT
、ABC $ITEM_#1_VALUE$ QWERT
、ABC $item_#1_Value$ QWERT
都需要替换成ABC1234QWERT
.
我明白应该使用 preg_replace(...)
而不是 str_ireplace(...)
,但我不知道应该使用哪种正则表达式模式。
使用正则表达式的一种方法是将您的标签与可选的周围多个空格相匹配:
\s*$item_#1_Value$\s*
PHP代码
<?php
$strings[] = 'ABC$item_#1_Value$QWERT';
$strings[] = 'ABC $ITEM_#1_VALUE$ QWERT';
$strings[] = 'ABC $item_#1_Value$ QWERT';
foreach ($strings as $string) {
$string = preg_replace('/\s*$item_#1_Value$\s*/i', "1234", $string);
echo $string.PHP_EOL;
}
结果
ABC1234QWERT
ABC1234QWERT
ABC1234QWERT