Help with regular expressions

Hi,

I’d like to replace every occurrence of a string unless it’s preceeded by another specific string. So, for example ‘Smith’ should become ‘Mr Smith’ but ‘Agent Smith’ shouldn’t become ‘Agent Mr Smith’

This could probably go in the Perl subforum but PHP guys should have this down pat too.

Thanks

The ^ caret symbol sign in a regular expression will ensure that the match occurs at the start.

You will want to use str_replace along with the [url=“http://www.regular-expressions.info/anchors.html”]start of string caret symbol.

So let’s say I have a string
“Let’s go talk to Agent Smith. Hello, Smith.”

It needs to become
“Let’s go talk to Agent Smith. Hello, Mr Smith.”

How do I write that regular expression? (I think I should use preg_replace rather than str_replace?)

That’s a different situation from the one that I was proposing.

Where you were saying:

unless it’s preceeded by another specific string

will the PHP script be expected to know that it should not replace when specifically “Agent” is beforehand?

And what if Agent Smith is a woman?

Yes, a if specific string (in my example Agent) comes before the string that is to be replaced, then it shouldn’t be replaced.

Oh, it’s just a simple example. I didn’t want to complicate things with my actual script.

By using negative lookbehind

I’m no regular expression expert, but it should be something like:

(?<!Agent)\s(Smith)

Thanks, that’s just the kind of think I need.