繁体   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