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
https://forums.phpfreaks.com/topic/182618-preg_replace-with-a-character/
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_-]#"

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);

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.