如何使用PHP从字符串中删除不需要的字符?

时间:2016-07-13 11:19:16

标签: php

我需要从给定的字符串中删除一些字符。

$mystring = 'test1 ( 07/07/2016) x 1 - 300.00 test2 test 2 (12/7/2016) x 1 - 82.00';

在这里,我只需要获得test1和test2 test2我该如何实现?

3 个答案:

答案 0 :(得分:0)

使用正则表达式获取任何日期,然后获取字符串

$mystring = 'test1 ( 07/07/2016) x 1 - 300.00 test2 test 2 (12/7/2016) x 1 - 82.00';

$mystring = preg_replace('#\( ?\d\d/\d?\d/\d\d\d\d\) ?x ?1 ?- ?[\d\.]+#', '', $mystring);
echo $mystring;

答案 1 :(得分:0)

您可以使用str_replace()

试试这个:

$mystring = 'test1 ( 07/07/2016) x 1 - 300.00 test2 test 2 (12/7/2016) x 1 - 82.00';
$removable_string = "( 07/07/2016) x 1 - 300.00";
echo str_replace($removable_string, '', $mystring); // test1 test2 test 2 (12/7/2016) x 1 - 82.00

答案 2 :(得分:0)

使用preg_replace()将第一个参数作为正则表达式数组,您可以过滤掉不需要的文本,只留下相关的文本:

   <?php

        $myString       = 'test1 ( 07/07/2016) x 1 - 300.00 test2 test 2 (12/7/2016) x 1 - 82.00';

        // REMOVE ALL DATES WITHIN PARENTHESIS AS WELL AS ALL STRINGS NOT
        // RELATED TO THE STRING test FROM THE STRING $myString USING
        // preg_replace WITH AN ARRAY OF REGEX AS 1ST PARAMETER:
        $rxDates        = array(
            "#(\(\d{1,2}\/\d{1,2}\/\d{4}\))#si",
            "#(\(\s*\d{1,2}\/\d{1,2}\/\d{4}\))#si",
            "#(x\s*\d{1}\s*\-\s*\d{1,7}\.\d{2})#si",
        );
        $cleanString    = trim(preg_replace($rxDates, "", $myString));

        var_dump($cleanString);
        // DUMPS:==> 'test1   test2 test 2'

        // YOU CAN GO A STEP FURTHER REMOVING SPACES AS IN 'test 2'
        $cleanString    = preg_replace("#(test)(\s*)(\d*)#", "$1$3", $cleanString);

        var_dump($cleanString);
        // DUMPS:==> 'test1   test2 test2'

        // YOU MAY WANT TO PUT THEM IN AN ARRAY IN WHICH CASE 
        // YOU MAY DO SOMETHING LIKE THIS:
        $arrCleanString = preg_split("#\s{1,10}#", $cleanString);

        var_dump($arrCleanString);
        // DUMPS:               
        array (size=3)
          0 => string 'test1' (length=5)
          1 => string 'test2' (length=5)
          2 => string 'test2' (length=5)
相关问题