[英]How to replace html tag with other tags using preg-match?
I have a string like the following. 我有一个类似下面的字符串。
<label>value1<label>:value<br>
<label>value2<label>:value<br>
<label>value3<label>:value<br>
and i need to arrange this as following 我需要安排如下
<li><label>value1<label><span>value</span><li>
i have tried for this last 2 days, but no luck.Any help? 我已经尝试了这最后两天,但没有运气。有帮助吗?
This really isn't something you should do with regex. 这真的不是您应该使用正则表达式执行的操作。 You might be able to fudge together a solution that works provided it makes a lot of assumptions about the content it's parsing, but it will always be fragile and liable to break should that content deviate from the expected by any significant degree.
如果它对要解析的内容进行了很多假设,您也许可以将一个可行的解决方案组合在一起,但是,如果该内容与预期的任何重大偏离,它将始终脆弱且易于破坏。
A better bet is using PHP's DOM family of classes. 更好的选择是使用PHP的DOM系列类。 I'm not really at liberty to write the code for you (and that's not what SO is for anyway), but I can give you a pointer regarding the steps you need to follow.
我并不是真正为您编写代码的人(无论如何这不是SO的意思),但是我可以为您提供有关您需要遵循的步骤的指导。
If, for the sake of regex, you should use it then follow as below : 如果为了正则表达式,您应该使用它,请按照以下步骤操作:
$string = <<<TOK
<label>value1<label>:value<br>
<label>value2<label>:value<br>
<label>value3<label>:value<br>
TOK;
preg_match_all('/<label>(.*?)<label>\:(.*?)<br>/s', $string, $matches);
print_r($matches);
/*
Array
(
[0] => Array
(
[0] => value1:value
[1] => value2:value
[2] => value3:value
)
[1] => Array
(
[0] => value1
[1] => value2
[2] => value3
)
[2] => Array
(
[0] => value
[1] => value
[2] => value
)
)
*/
$content = "";
foreach($matches as $key => $match)
{
$content.= "<li><label>{$matches[1][$key]}<label><span>{$matches[2][$key]}</span><li>\n";
}
echo($content);
/*
Output:
<li><label>value1<label><span>value</span><li>
<li><label>value2<label><span>value</span><li>
<li><label>value3<label><span>value</span><li>
*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.