tôi đã viết mã PHP này để thực hiện một số thay:Cách sử dụng biểu thức chính quy của preg_replace PHP để tìm và thay thế văn bản?
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% <+.');
Kết quả thành này:
The fruit I most like is: <span class="P"> <span>apple</span> <span>banna</span> <span>orange</span> </span>.
Tuy nhiên tôi cần thiết để xác định thẻ div của trái cây, như thế này:
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>.
Tôi muốn mua một loại trái cây để khám phá một biểu thức chính quy để thực hiện điều này :-)
Whit sự giúp đỡ Xavier Barbosa, tôi đến sollution thức này:
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
}
lớp của khoảng cách bên trong (s) (tức là class = "b") luôn bằng chữ cái đầu tiên của quả? – Ass3mbler
Bạn có viết ngôn ngữ khuôn mẫu của riêng bạn trong PHP không? Hãy coi chừng [BobX] (http://thedailywtf.com/Articles/We-Use-BobX.aspx). – Nathan
Ass3mbler, xin lỗi, tôi không có ý định tạo mối quan hệ với chữ cái đầu tiên của nội dung. Tôi đã chỉnh sửa tên lớp thành một cái gì đó như: t1, t2 và t3. – Roger