Jump to content

preg_replace with a character '-'


e111982

Recommended Posts

Hi. I have a replace problem. I have strings as:

 

$old1="danger";

$old2="non-danger";

 

$new1="dangerous";

$new2="safe";

 

$str="A typical explosives factory is divided into two parts: the 'non-danger' and 'danger' areas.";

 

echo preg_replace("~\b$old\b~i", $new, $str);

 

And I want an output as:

 

A typical explosives factory is divided into two parts: the 'safe' and 'dangerous' areas.

 

It gives as:

 

A typical explosives factory is divided into two parts: the 'non-dangerous' and 'dangerous' areas.

 

Thanks for your help.

 

Link to comment
Share on other sites

It's because \b matches a word boundary, which checks if the character before/after is [^a-zA-Z0-9_]. If you wish to match - as not being a word boundary you will probably have to use your own character set to emulate \b. Untested, but something like...

 

"#[^a-z-A-Z0-9_-]$old[^a-z-A-Z0-9_-]#"

Link to comment
Share on other sites

This code is not working. Where is the error? Thanks.I am new.

 

$old="danger";

 

$new="danger2";

 

$str="A typical explosives factory is divided into two parts: the 'non-danger' and 'danger' areas.";

 

echo preg_replace("#[^a-z-A-Z0-9_-]$old[^a-z-A-Z0-9_-]#", $new, $str);

Link to comment
Share on other sites

Hmm... I think I got it, if I did, it turns out it's fairly simple.

 

#(?<![a-zA-Z0-9_-]){$old}(?![a-zA-Z0-9_-])#"

 

I'm sure if I'm too far off base somebody with a bit more experience will chime in, but at a quick test it seems to work.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.