2016-09-30 51 views
1

我有以下字符串字符串的出现次数:替换对应于正则表达式

$a = "test1"; 
$b = "test 2"; 
$c = "test<3"; 
$d = "test&4"; 

我想通过一些字母,以取代“&”后面出现,并通过终止“;”。

输出应该是:

$a = "test1"; 
$b = "test 2"; 
$c = "test 3"; 
$d = "test&4"; 

我如何能做到这一点用PHP?

回答

2

使用此:

$x = preg_replace('/&[a-z]+;/', ' ', $b); 
echo $x; 
4

在这种特殊情况下,你并不需要一个正则表达式,很有可能你需要的是对HTML实体进行解码,并可以与html_entity_decode()中完成,如:

$a = html_entity_decode("test1"); 
$b = html_entity_decode("test 2"); 
$c = html_entity_decode("test<3"); 
$d = html_entity_decode("test&4"); 

var_dump($a,$b,$c,$d); 
+1

该解决方案将返回'“TES t <3“,而OP需要”测试3“。 –

1

的答案@ this.lau_是最好的,但如果你想在正则表达式,试试这个

(\&)([a-z]{1,4})(;)