您好我如何在
上进行preg匹配$string1 = "[%refund%]processed_by"
$string2 = "[%refund%]date_sent"
我想抓住%%中的位,然后完全删除[%item%]
。只留下“proccessed_by”或“date_sent”我已经走了下去,但有点卡住了。
$unprocessedString = "[%refund%]date_sent"
$match = preg_match('/^\[.+\]/', $unprocessedString);
$string = preg_replace('/^\[.+\]/', $unprocessedString);
echo $match; // this should output refund
echo $string; // this should output date_sent
答案 0 :(得分:2)
您的问题在于使用preg_match
功能。它返回找到的匹配项的数字。但是如果将变量作为第三个参数传递给它,它会将整个模式及其子模式的匹配存储在一个数组中。
因此,您可以使用preg_match
捕获子模式中所需的两个部分,这意味着您不需要preg_replace
:
$unprocessedString = "[%refund%]date_sent"
preg_match('/^\[%(.+)%\](.+)/', $unprocessedString, $matches);
echo $matches[1]; // outputs 'refund'
echo $matches[2]; // outputs 'date_sent'