【问题标题】:preg_replace all characters up to a certain onepreg_replace 直到某个字符的所有字符
【发布时间】:2011-01-20 23:09:22
【问题描述】:

我有一个字符串

&168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&

我必须删除,比如说,这部分 &185601651932|mobile|3|120|1&(以 amp 开头,以 amp 结尾)只知道第一个直到垂直线的数字(185601651932)

所以结果我会有

&168491968426|mobile|3|100|1&114192088691|mobile|3|555|5&

我怎么能用 PHP preg_replace 函数做到这一点。行 (|) 分隔值的数量始终相同,但 id 仍然喜欢灵活的模式,而不取决于 & 符号之间的行数。

谢谢。

附:此外,我会很高兴链接到一个很好的简单编写的资源,该资源与 php 中的正则表达式相关。 google 中有很多这样的 :) 但也许你碰巧有一个 非常棒的链接

【问题讨论】:

    标签: php preg-replace


    【解决方案1】:
    preg_replace("/&185601651932\\|[^&]+&/", ...)
    

    广义的,

    $i = 185601651932;
    preg_replace("/&$i\\|[^&]+&/", ...);
    

    【讨论】:

    • 是的!而已!除了,我不需要最后的 &,所以它只是 preg_replace("/&185601651932\\|[^&]+/", ...) 非常感谢
    【解决方案2】:

    如果您想要真正的灵活性,请使用 preg_replace_callback。 http://php.net/manual/en/function.preg-replace-callback.php

    【讨论】:

      【解决方案3】:

      重要提示:不要忘记使用preg_quote() 转义您的号码:

      $string = '&168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&';
      $number = 185601651932;
      if (preg_match('/&' . preg_quote($number, '/') . '.*?&/', $string, $matches)) {
          // $matches[0] contains the captured string
      }
      

      【讨论】:

        【解决方案4】:

        在我看来,您应该使用另一种数据结构而不是字符串来处理这些数据。 我希望这些数据采用类似

        的结构
        Array(
          [id] => Array(
             [field_1] => value_1
             [field_2] => value_2
          )
        )
        

        您可以通过执行以下操作将您的巨大字符串按摩成这样的结构:

        $data_str = '168491968426|mobile|3|100|1&185601651932|mobile|3|120|1&114192088691|mobile|3|555|5&';
        $remove_num = '185601651932';
        
        /* Enter a descriptive name for each of the numbers here 
        - these will be field names in the data structure */
        $field_names = array( 
            'number',
            'phone_type',
            'some_num1',
            'some_num2',
            'some_num3'
        );
        
        /* split the string into its parts, and place them into the $data array */
        $data = array();
        $tmp = explode('&', trim($data_str, '&'));
        foreach($tmp as $record) {
            $fields = explode('|', trim($record, '|'));
            $data[$fields[0]] = array_combine($field_names, $fields);
        }
        
        echo "<h2>Data structure:</h2><pre>"; print_r($data); echo "</pre>\n";
        /* Now to remove our number */
        unset($data[$remove_num]);
        echo "<h2>Data after removal:</h2><pre>"; print_r($data); echo "</pre>\n";
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-01
          • 2012-04-10
          • 2018-01-26
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多