簡體   English   中英

正則表達式和preg_match_all問題

[英]Problem with regex and preg_match_all

我也有一個很長的字符串類似:

$text = "[23,64.2],[25.2,59.8],[25.6,60],[24,51.2],[24,65.2],[3.4,63.4]";

它們是坐標。 我想從我真的討厭正則表達式的[]中提取每個x,y,但仍然存在正確編寫它的問題

我試過了

$pattern = "#\[(.*)\]#";
preg_match_all($pattern, $text, $matches);

但這沒有用。 有人可以幫我嗎?

您應該使用.*? 減少貪婪 否則,它可能會匹配太長的子字符串。 在您的情況下,使用否定字符類([^[\\]]*)有時也很有幫助。

但是,始終最好對您想要的內容更加具體:

preg_match_all("#\[([\d,.]+)]#", $text, $matches);

這樣,它將僅匹配\\ d逗號,逗號和點。 糟糕,並且[需要逃脫。

preg_match_all("#\[([\d.]+),([\d.]+)]#", $text, $matches, PREG_SET_ORDER);

會給您X和Y坐標分開的。 也嘗試將PREG_SET_ORDER作為第四個參數,這將為您提供:

Array
(
    [0] => Array
        (
            [0] => [23,64.2]
            [1] => 23
            [2] => 64.2
        )

    [1] => Array
        (
            [0] => [25.2,59.8]
            [1] => 25.2
            [2] => 59.8
        )

    [2] => Array
        (
            [0] => [25.6,60]
            [1] => 25.6
            [2] => 60
        )

您需要使星號“懶惰”:

$pattern = "#\[(.*?)\]#";

但是呢?

$pattern = "#\[(\d+(\.\d+)?),(\d+(\.\d+)?)\]#";

在您的代碼上,這將產生

Array
(
    [0] => Array
        // ...

    [1] => Array
        (
            [0] => 23
            [1] => 25.2
            [2] => 25.6
            [3] => 24
            [4] => 24
            [5] => 3.4
        )

    [2] => Array
        //...

    [3] => Array
        (
            [0] => 64.2
            [1] => 59.8
            [2] => 60
            [3] => 51.2
            [4] => 65.2
            [5] => 63.4
        )

    [4] => Array
        //...
)

應該這樣做:

$string = '[23,64.2],[25.2,59.8],[25.6,60],[24,51.2],[24,65.2],[3.4,63.4]';
if (preg_match_all('/,?\[([^\]]+)\]/', $string, $matches)) {
  print_r($matches[1]);
}

它打印:

[0] => string(7) "23,64.2"
[1] => string(9) "25.2,59.8"
[2] => string(7) "25.6,60"
[3] => string(7) "24,51.2"
[4] => string(7) "24,65.2"
[5] => string(8) "3.4,63.4"

正則表達式的分解:

,?        // zero or one comma
\[        // opening bracket
([^\]]+)  // capture one or more chars until closing bracket
\]        // closing bracket

要獲取x,y坐標,您可以:

$coords = array();
foreach ($matches[1] as $match) {
  list($x, y) = explode(',', $match);
  $coords[] = array(
     'x' => (float)$x,
     'y' => (float)$y
  );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM