-1

I have these 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 won't be replaced. Like this.

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

It's not working! (of course 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 won't be replaced.

3
  • does string 2 always follow string 1 or can it be anywhere? Commented Jan 29, 2013 at 2:08
  • First: This is a good tutorial: regular-expressions.info/tutorialcnt.html - If you have specific points where you're getting stuck, ask a specific question about that point. Commented Jan 29, 2013 at 2:09
  • I really love RegexBuddy. Use it to build, explain, test and debug regular expressions. Commented Jan 29, 2013 at 2:14

2 Answers 2

2
$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
Sign up to request clarification or add additional context in comments.

2 Comments

Whatif i want to do exactly as I said but by using arrays? preg_replace ($arr.(?! $arr2,$replacewitharray ,$instring) (just fast example)
@Kilise: what do you want to achieve? Regular expression is always a string. Your question looks like "what I want to do the same but by using orange"
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.