简体   繁体   中英

preg_replace php regex

Okey I got two questions.

Number one. I really suck at regex, it just can't get into my head. Any ideas how to think or learn, any good tutorials? (I've searched and i find them , for being tutorials, too advanced.)

Number two:

Lets say i got those 3 strings:

$string = "his";

$str1 = "hi";
$str2 = "s";

So what I want to do is a regex that looks for hi and replaces it. But! if there is "s" in the string it wont be replaced. Like this.

preg_replace('/'.$str1.'^['.$str2.']/',"replace it with this",$string);

It's not working! (ofcourse not, regex isn't my thing!)

As I said, I don't get this with regex. I want to find str1 and if str2 isn't in the string it wont be replaced. Anyone?

$str = 'his';

$s1 = 'hi';
$s2 = 's';

$result = preg_replace('~' . preg_quote($s1) . '(?!' . preg_quote($s2) . ')~', 'replace with this', $str);
                      // ~hi(?!s)~
                      // this regex means:
                      //   "hi" string followed by anything but "s"

var_dump($result);

Live examples:

  1. http://ideone.com/XjX9n3
  2. http://ideone.com/U2JdkL

I think you want to make multiple filters, like: s , m etc or more..

$s = array('s', 'm');
$result = preg_replace('~hi(?!'. join('|', $s) .')~', 'replace with this', 'him');
print $result; // him
// and
$result = preg_replace('~hi(?!'. join('|', $s) .')~', 'replace with this', 'hiz');
print $result; // replace with thisz

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