2

Let's say I have this string:

$myString = 'aaa = b AND cc = dd OR e = ff_%_g AND hh = iii AND j = k_%_lll ...'

I want to check if the substring '_%_' is present, and in that case, I want to replace the previous (and only the previous) '=' by a 'LIKE'.

Namely, I want this:

$myString = 'aaa = b AND cc = dd OR e LIKE ff_%_g AND hh = iii AND j LIKE k_%_lll ...'

I know how to replace all the '=' using strpos() and substr_replace(), but I need to replace only those that precede a '_%_'

Any help, please?

1 Answer 1

2

Here you go:

$myString = preg_replace("/=([^=]*_%_[^ ]*)/", "LIKE $1", $myString);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks mate! Don't know why, but I think I'll never get along well with regexps :)
@hek2mgl, can you explain your edit? Shouldn't it work fine without that?
@MikO No, without the [^ ]* it would make foo_%_ out of foo_%_bar. The answer was basically good, so I decided to edit this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.