【发布时间】:2016-05-13 17:20:09
【问题描述】:
我正在尝试将旧的preg_replace 转换为preg_replace_callback,但非常努力。想知道是否有人可以帮忙。
我的旧工作:
$pattern = "/\[product\](.+?)\[\/product\]/e";
$text = "Hejsan hoppsan [product]2022|lots of text textext[/product] och sen så händer det lite blandat och så har vi [product]11245| med en jävla massa text[/product]";
echo preg_replace($pattern, "productBox('$1')", $text);
只要在| 之后和[/product] 之前没有新行,就可以了。
[product]2022| like
this
dont
work[/product]
但除此之外代码工作正常。
功能:
function productBox($text) {
global $wpdb;
$test = explode("|",$text);
$loopProductID = $test[0];
$desc = $test[1];
//sql's to get information about the products
$productHTML = '<div class="flow-item">
<div class="flow-product-image"><a href="'.$permalink.'"><img src="'.$thumburl.'" alt="'.$title.'" /></a></div>
<div class="flow-product-info">
<h3><a href="'.$permalink.'">'.$title.'</a></h3>
<div style="padding: 5px 0px 10px;">'.$desc.'</div>
<div class="flow-product-facts">Art.nr: '.$artnr.' - Pris: '.$prisinklmoms.' kr</div>
</div>
<div class="clear"></div>
</div>';
return $productHTML;
}
我也试过把整个函数放在preg_replace_callback里面,像这样:
$test = preg_replace_callback($pattern,
function productBox($matches) {
global $wpdb;
$test = explode("|",$matches);
$loopProductID = $test[0];
$desc = $test[1];
//sql's to get information about the products
$productHTML = '<div class="flow-item">
<div class="flow-product-image"><a href="'.$permalink.'"><img src="'.$thumburl.'" alt="'.$title.'" /></a></div>
<div class="flow-product-info">
<h3><a href="'.$permalink.'">'.$title.'</a></h3>
<div style="padding: 5px 0px 10px;">'.$desc.'</div>
<div class="flow-product-facts">Art.nr: '.$artnr.' - Pris: '.$prisinklmoms.' kr</div>
</div>
<div class="clear"></div>
</div>';
return $productHTML;
}
, $text);
返回一个白页。
//sql's to get information about the products 包含相当多的 sql,所以我把它拿走了,因为它会是一个很长的帖子,而且 sql 工作正常。
谁能帮帮我?
最好的解决方案是如果我可以在没有在 preg_replace_callback 中创建函数的情况下使用它,因为代码将在更多地方使用,并且一遍又一遍地创建函数似乎很糟糕,以防我不得不更改某些内容在里面。所以我宁愿只调用这个函数。
或者有没有办法多做呢?把整个东西放在一个函数中,然后像myGoodFunction($text_I_want_fixed);一样调用它?
[product]productid|Text about the product to show[/product]
这就是它现在的制作方式,我一直在考虑尝试更改正则表达式以使其像[product id="productid"]Text[/product] 但那是以后的修复。只是想弄清楚如何修复preg_replace_callback。
提前感谢您的帮助!
【问题讨论】:
标签: php regex preg-replace preg-replace-callback