2013-08-17 45 views
1

我需要根据简单的special characters like _ and |定期删除字符串的某些部分。这里是我的代码:使用preg_replace删除字符串。还有其他的选择吗?

<?php 
$text = "a*a1.zip,a2.zip|b*b1.zip|c*c1.zip|d*d1.zip|e*e1.zip|f*f1.zip|g*g1.zip|h*h1.zip"; 
$expl = explode("|", $text); 
print_r($expl); 
?> 

我需要删除所有的alphabets and *'s, |'s这样,我的输出应该是这样的:

a1.zip,a2.zip,b1.zip,c1.zip,d1.zip,e1.zip,f1.zip,g1.zip,h1.zip

我想使用preg_replace但它很难理解:(。还有其他的选择吗?在此先感谢...

回答

2

你可以使用preg_match来代替,但你仍然需要让你的正则表达式正确,所以它不一定会更容易。如果您希望使用的东西没有正则表达式,尝试双explode

$text = "a*a1.zip,a2.zip|b*b1.zip|c*c1.zip|d*d1.zip|e*e1.zip|f*f1.zip|g*g1.zip|h*h1.zip"; 
$expl = explode("|", $text); 
foreach ($expl as $part) { 
    // PHP 5.4+ 
    $values[] = explode('*', $part)[1]; 

    // OR PHP < 5.4 
    $tempvar = explode('*', $part); 
    $values[] = $tempvar[1]; 

    // Choose one of the above, not both 
} 
$string = implode(',', $values); 
1

试试这个。我没有测试这个。但你可以得到一个提示

<?php 
    $text = "a*a1.zip,a2.zip|b*b1.zip|c*c1.zip|d*d1.zip|e*e1.zip|f*f1.zip|g*g1.zip|h*h1.zip"; 


    $expl = explode("|", $text); 

    // YOU HAVE TO REMOVE a*, b*, c* which will be the first 2 characters after exploding. avoid this first 2 characters using substr 

    foreach($expl as $key=>$value) { 

     $result[] = substr($value,2); 

    } 

    $result_string = implode(',', $result); 

    ?> 
1

单排不preg_

$result_string = implode(',',array_map(function($v){return substr($v,strpos($v,'*')+1);},explode('|',$text)));