【问题标题】:How to create Array from a String with preg_match in PHP [duplicate]如何在 PHP 中使用 preg_match 从字符串创建数组 [重复]
【发布时间】:2019-02-14 19:26:19
【问题描述】:

我有如下字符串

Ref ID =={1234} [201] (text message)

我想创建一个像下面这样的数组

array(
    0 => 1234,
    1 => 201,
    2 => "text message"
)

现在我正在使用 Exploding the string 方法,但是它需要 8 行编码,并且像下面这样多次爆炸。

$data = array();
$str = 'Ref ID =={1234} [201] (text message)';
$bsArr1 = explode('}', $str);

$refIdArr = explode('{', $bsArr1);
$data[0] = $refIdArr[1];

$bsArr2 = explode(']', $bsArr[1]);
$codeArr = explode('[', $bsArr2[0]);
....
....
....

有没有办法通过 preg_match 实现这一点?

【问题讨论】:

  • 你有没有尝试过?
  • @revo 我已经通过多次爆炸实现了它,但不知道是否可以通过 preg_match 实现它。
  • 只要是文本处理,就可以使用正则表达式。但是社区希望看到您对自己想要的东西的尝试。

标签: php preg-match


【解决方案1】:

这将找到[{( 之一并捕获所有关注}]) 的懒惰

$str = "Ref ID =={1234} [201] (text message)";

preg_match_all("/[{|\[|\(](.*?)[\]|\)\}]/", $str, $matches);
var_dump($matches);

输出:

array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(6) "{1234}"
    [1]=>
    string(5) "[201]"
    [2]=>
    string(14) "(text message)"
  }
  [1]=>
  array(3) {
    [0]=>
    string(4) "1234"
    [1]=>
    string(3) "201"
    [2]=>
    string(12) "text message"
  }
}

https://3v4l.org/qKlSK

【讨论】:

    【解决方案2】:

    简单的预赛:

    preg_match('/{(\d+)}.*\[(\d+)].*\(([a-zA-Z ]+)\)/', 'Ref ID =={1234} [201] (text message)', $matches);
    
    $arr[] = $matches[1];
    $arr[] = $matches[2];
    $arr[] = $matches[3];
    
    echo '<pre>';
    var_dump($arr);
    die();
    

    【讨论】:

    • 这是一个非常硬编码的 preg_match 版本...3v4l.org/Ki9kO
    • @Edgar 感谢您的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 1970-01-01
    • 2011-06-17
    相关资源
    最近更新 更多