2012-11-16 103 views
1

我有|分开的特殊字符的列表中删除一个清单的字符,可以说$chars = "@ | ; | $ |";PHP从其他

我有一个字符串,比方说$stringToCut = 'I have @ list ; to Cut';

我想从$stringToCut全部删除字符在$chars

我该怎么做?

提前THX

回答

3

我会转换你的角色的列表中删除一个数组,并使用str_replace

$chars_array = explode($chars); 
// you might need to trim the values as I see spaces in your example 

$result = str_replace($chars_array, '', $stringToCut); 
1

使用preg_replace()删除

<?php 
$chars = "@ | ; | $ |"; 

$stringToCut = 'I have @ list ; to Cut'; 
$pattern = array('/@/', '/|/', '/$/', '/;/'); 
$replacement = ''; 
echo preg_replace($pattern, $replacement, $stringToCut); 

?> 
1

好,而不是使用正则表达式,只是爆炸的字符清单:

$chars = explode('|',str_replace(' ','','@ | ; | $ |'));//strip spaces, make array 
echo str_replace($chars,'',$string); 

str_replace接受数组作为第一个和/或第二个参数,也是see the docs
这使您可以用不同的对象替换每个字符,或者(正如我在此处所做的那样)将它们全部替换为全部(也就是将其删除)。

+0

@vladimire:我也在爆炸它,我只是在爆炸之前从列表中删除所有空格。如果你的字符串真的是'@ | ; | $',你正在替换像''的子字符串; '< - 空格 - 半角冒号空格。这是唯一的区别。就这样你知道 –