【问题标题】:Php split string on different charactersphp在不同的字符上拆分字符串
【发布时间】:2011-07-13 21:32:05
【问题描述】:

我想将字符串拆分为不同的字符,我想知道“拆分器”是什么。

字符串可以是例如:

"address=test"
"number>20"
"age<=55"

在这些情况下,我想获取名称、分隔符和数组中的值。

array[0]='address';
array[1]='=';
array[2]='test';

分隔符是 =,==,!=,,>=,

谁能告诉我处理这个问题?

【问题讨论】:

  • ([a-zA-Z]+)(=|==|!=||>=|

标签: php regex split


【解决方案1】:
$strings = array("address=test","number>20","age<=55");
foreach($strings as $s)
{
  preg_match('/([^=!<>]+)(=|==|!=|<|>|>=|<=)([^=!<>]+)/', $s, $matches);
  echo 'Left: ',$matches[1],"\n";
  echo 'Seperator: ',$matches[2],"\n";
  echo 'Right: ',$matches[3],"\n\n";
}

输出:

Left: address
Seperator: =
Right: test

Left: number
Seperator: >
Right: 20

Left: age
Seperator: <=
Right: 55

编辑:此方法使用 [^=!] 使该方法更喜欢完全失败而不是给出意外结果。这意味着foo=bar&lt;3 将无法被识别。这当然可以根据您的需要进行更改:-)。

【讨论】:

    【解决方案2】:

    未经测试但应该可以工作:

    $seps=array('=', '==', '!=', '<', '>', '>=', '<=');
    
    $lines=array(
        "address=test",
        "number>20",
        "age<=55"
        );
    
    foreach ($lines as $line) {
        $result=array();
        foreach ($seps as $sep) {
            $offset=strpos($line, $sep);
            if (!($offset===false)) {
                $result[0]=substr($line, 0, $offset);
                $result[1]=substr($line, $offset, 1);
                $result[2]=substr($line, $offset+1);
            }
        }
        print_r($result);
    }
    

    然后,您可以使用count($result) 测试$result 中是否有任何内容(找到拆分字符)。

    【讨论】:

      【解决方案3】:
      preg_match('/(\S)(=|==|!=|<|>|>=|<=)(\S)/', $subject, $matches)
      

      【讨论】:

        【解决方案4】:

        又快又脏:

        $parts = preg_split('/[<>=!]+/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
        

        【讨论】:

          【解决方案5】:

          试试这个:

          list($key, $splitter, $val) = split('[^a-z0-9]+', $str);
          echo 'Key: '.$key.'; Splitter: '.$splitter.'; Val: '.$val;
          

          这假定您的键和值是字母数字。希望对你有帮助:)

          【讨论】:

            【解决方案6】:

            试试:

            $str = "address=test";
            preg_match("/(?<k>.+?)(?<operator>[=|==|!=|<|>|>=|<=]{1,2})(?<v>.+?)/",$str,$match); 
            $match["k"] //addres
            $match["operator"] //=
            $match["v"] //test
            

            【讨论】:

            • 查看这个:“[=|==|!=||>=|]{1,2} 或 ([=|==|!=||>=|
            猜你喜欢
            • 2010-09-27
            • 2011-01-08
            • 2015-08-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多