假设我有一个字符串,例如:
$text = "<object>item_id1a2b3</object>xxx<object>item_id4c5d6</object>"
我想将其转换为:%ITEM:1a2b3xxx%ITEM:4c5d6
这是我所拥有的:
$text = preg_replace("/<object.*item_id([a-zA-Z0-9]+).*<\/object/","%ITEM:$1",$text);
这不太正确,因为搜索是贪婪的。
想法?
谢谢!
假设我有一个字符串,例如:
$text = "<object>item_id1a2b3</object>xxx<object>item_id4c5d6</object>"
我想将其转换为:%ITEM:1a2b3xxx%ITEM:4c5d6
这是我所拥有的:
$text = preg_replace("/<object.*item_id([a-zA-Z0-9]+).*<\/object/","%ITEM:$1",$text);
这不太正确,因为搜索是贪婪的。
想法?
谢谢!
试试这个:
$text = preg_replace("/<object>.*?item_id([a-zA-Z0-9]+).*?<\/object/","%ITEM:$1",$text);
注意:未经测试
我所做的是将 .* 更改为 .*?,并关闭您的对象标签(我认为这可能是一个错误;如果不正确,请见谅)。这 ?在 .* 之后应该让它变得懒惰。
我们可以使用 *? 代替*。所以最终的正则表达式变为:
$text = preg_replace("/<object.*?item_id([a-zA-Z0-9]+).*?<\/object>/","%ITEM:$1",$text);
我还在正则表达式的末尾添加了“>”,以避免它出现在被替换的文本中。
那么为什么不这样做:
$text = preg_replace("@<object>item_id([a-zA-Z0-9]+)</object>@", "%ITEM:$1", $text);
或者像这样:
$text = preg_replace("@<object>item_id@", "%ITEM:", $text);
$text = preg_replace("@</object>@", "", $text);
注意:经过测试=)
用于$2下一个括号。
在“”的每个实例上拆分字符串不是更容易吗?
$result = '';
$items = explode('<object>', $text);
foreach ($items as $item){
$result .= '%'.str_replace('</object>', '', $item);
}
echo $result;