使用preg_replace删除字符串。还有其他选择吗?

时间:2013-08-17 06:50:55

标签: php string replace preg-replace

我需要根据简单的special characters like _ and |定期删除字符串的某些部分。这是我的代码:

<?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,但很难理解:(。还有其他选择吗?提前谢谢......

3 个答案:

答案 0 :(得分: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 :(得分: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);

    ?>

答案 2 :(得分:1)

没有preg_

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