gpt4 book ai didi

php - 如何使用PHP preg_replace 正则表达式查找和替换文本?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:42:49 24 4
gpt4 key购买 nike

我写了这段 PHP 代码来做一些替换:

function cambio($txt){
$from=array(
'/\+\>([^\+\>]+)\<\+/', //finds +>text<+
'/\%([^\%]+)\%/', //finds %text%
);

$to=array(
'<span class="P">\1</span>',
'<span>\1</span>',
);

return preg_replace($from,$to,$txt);
}

echo cambio('The fruit I most like is: +> %apple% %banna% %orange% <+.');

结果是:

The fruit I most like is: <span class="P"> <span>apple</span> <span>banna</span> <span>orange</span> </span>.

但是我需要识别水果的 span 标签,如下所示:

The fruit I most like is: <span class="P"> <span class="t1">apple</span> <span class="t2">banana</span> <span class="t3">coco</span> </span>.

我会买一个水果给谁发现一个正则表达式来完成这个:-)


在 Xavier Barbosa 的帮助下,我得出了这个最终解决方案:

function matches($matches){
static $pos=0;
return sprintf('<span class="t%d">%s</span>',++$pos,$matches[1]);
}

function cambio($txt){//Markdown da Atípico : Deve ser usado depois do texto convertido para markdown
$from=array(
'/\=>(.+?)<\=/', //finds: =>text<=
'/\+>(.+?)<\+/', //finds +>text<+
);

$to=array(
'<span class="T">\1</span>',
'<span class="P">\1</span>',
);

$r=preg_replace($from,$to,$txt);
return preg_replace_callback('/%(.*?)%/','matches',$r);//finds %text%
//'/%((\w)\w+)%/' //option
}

最佳答案

<?php


function cambio($txt){
$from=array(
'/\+>(.+?)<\+/', //finds +>text<+
'/%((\w)\w+)%/', //finds %text%
);

$to=array(
'<span class="P">\1</span>',
'<span class="\2">\1</span>',
);

return preg_replace($from,$to,$txt);
}

echo cambio('The fruit I most like is: +> %apple% %banna% %orange% <+.');

以及 PHP5.3 的有状态版本

function cambio($txt) {
return preg_replace_callback('/\+>(.+?)<\+/', function ($matches) {
$txt = sprintf('<span class="P">%s</span>', $matches[1]);

return preg_replace_callback('/%(\w+)%/', function ($matches) {
static $pos = 0;
return sprintf('<span class="t%d">%s</span>', ++$pos, $matches[1]);
}, $txt);

}, $txt);
}

echo cambio('The fruit I most like is: +> %apple% %banna% %orange% <+.');

关于php - 如何使用PHP preg_replace 正则表达式查找和替换文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4684410/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com