簡體   English   中英

我的正則表達式有什么問題?

[英]What's wrong in my regular expression?

我只需要從下面幾行中獲得:喬尼(Jony),史密斯(Smith)和example-free@wpdevelop.com

如您所見,它們在^和〜之間。

text^name1^Jony~text^secondname1^Smith~text^email1^example-free@wpdevelop.com~

為此,我嘗試過:

preg_match_all ('/\^(.*?)\~/', $row['form'], $res);

對於名稱,它顯示: ^ name1 ^ Jony〜 ,第二個名稱: ^ secondname1 ^ Smith〜和電子郵件: ^email1^example-free@wpdevelop.com~

如您所見,“文本”一詞已消失,但^,name1,secondname1,email1和〜卻不消失。

您能告訴我我的正則表達式有什么問題嗎?

.*更改為[^^]*表示“ ^ 之外的任何字符”

<?php
$str = 'text^name1^Jony~text^secondname1^Smith~text^email1^example-free@wpdevelop.com~';

preg_match_all ('/\^([^^]*?)\~/', $str, $res);

var_dump($res);

/*
//output 

$ php scratch.php
array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(6) "^Jony~"
    [1]=>
    string(7) "^Smith~"
    [2]=>
    string(28) "^example-free@wpdevelop.com~"
  }
  [1]=>
  array(3) {
    [0]=>
    string(4) "Jony"
    [1]=>
    string(5) "Smith"
    [2]=>
    string(26) "example-free@wpdevelop.com"
  }
}
*/

您的正則表達式必須為'/\\^([^\\^]*?)\\~/' ,您正在使用. ,它選擇^ 您無需使用[^\\^]而不是來選擇^ .

這個更好:

<?php

$string = 'text^name1^Jony~text^secondname1^Smith~text^email1^example-free@wpdevelop.com~';

preg_match_all('/\^.+?\^(.+?)~/', $string, $matches);

var_dump($matches);

$ matches的結果將是:

array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(12) "^name1^Jony~"
    [1]=>
    string(19) "^secondname1^Smith~"
    [2]=>
    string(35) "^email1^example-free@wpdevelop.com~"
  }
  [1]=>
  array(3) {
    [0]=>
    string(4) "Jony"
    [1]=>
    string(5) "Smith"
    [2]=>
    string(26) "example-free@wpdevelop.com"
  }
}

我在正則表達式中添加了。+?\\ ^部分,它與兩個^字符之間的文本匹配。

暫無
暫無

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

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