简体   繁体   中英

What's wrong in my regular expression?

I need to get from the line below only these parts: Jony, Smith and example-free@wpdevelop.com

which, as you can see, they are between ^ and ~.

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

to do this I tried:

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

For the name it displays: ^name1^Jony~ for the second name: ^secondname1^Smith~ and email: ^email1^example-free@wpdevelop.com~

As you can see the word "text" has already disappeared, but not the ^, name1, secondname1, email1 and ~

Can you tell me what's wrong in my regular expression?

change .* to [^^]* meaning "Any character excluding ^ "

<?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"
  }
}
*/

Your regex needs to be '/\\^([^\\^]*?)\\~/' ,you're using . , which selects ^ . You need to not select ^ using [^\\^] rather than . .

This is better:

<?php

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

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

var_dump($matches);

The result in $matches will be:

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"
  }
}

I added this .+?\\^ part to the regular expression, it matches the text between the two ^ characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM