从字符串末尾删除NULL

时间:2012-11-13 13:05:32

标签: php arrays string function

如何在行尾删除NULL?

  

WYOMING MI NEW JERSEY 07728计算机维修技术

$phrases = array("NEW YORK NY", "NEW JERSEY", "SOUTH DAKOTA", "SOUTH CAROLINA",     "COMPUTER REPAIR TECH","YORK NY","07728","WYOMING MI","WYOMING MINNESOTA");
$string = ("I live in wyoming Minnesota, but used to live in New Jersey 07728 working     as a computer repair tech.");
$string = strtoupper($string);

$matches = stringSearch($phrases, $string);

var_dump($matches);

function stringSearch($phrases, $string){
    $phrases1 = trim(implode('|', $phrases));
    $phrases1 = str_replace(' ', '\s', $phrases1);

    preg_match_all("/$phrases1/s", $string, $matches);

    $value = implode(' ', array_filter($matches[0]));
    echo $value;

}

2 个答案:

答案 0 :(得分:2)

该功能不会返回任何内容。因此,$matches变量将包含值null。在函数内部var_dump($matches)字符串之后,该值由echo输出。

换句话说,它不是结果字符串的一部分,那些是单独的输出。删除var_dump($matches),它就消失了。

答案 1 :(得分:1)

导致问题的是var_dump

试一试!

$phrases = array("NEW YORK NY", "NEW JERSEY", "SOUTH DAKOTA", "SOUTH CAROLINA",     "COMPUTER REPAIR TECH","YORK NY","07728","WYOMING MI","WYOMING MINNESOTA");
$string = ("I live in wyoming Minnesota, but used to live in New Jersey 07728 working     as a computer repair tech.");
$string = strtoupper($string);

$matches = stringSearch($phrases, $string);

//var_dump($matches);  // <---------- comment this out!!!

function stringSearch($phrases, $string){
    $phrases1 = trim(implode('|', $phrases));
    $phrases1 = str_replace(' ', '\s', $phrases1);

    preg_match_all("/$phrases1/s", $string, $matches);

    $value = implode(' ', array_filter($matches[0]));
    if($value){
        echo $value;
    }

}