Jump to content

If a string contains "NOT word" how to replace it with "-word"?


the5thace

Recommended Posts

To catch the NOT at the start of the string and require a space in front of it using substr try this:

<?php

$mystring = ' abcNOT def';
$findme   = ' NOT ';
if (substr($mystring, 0, 4)=='NOT '){
    $new="-".substr($mystring, 4);
}else{
$new=str_replace($findme, ' -', $mystring);
}
echo $new;
?>

echo still ends with dog+not+cat

$Bquery = urlencode($_POST['query']);
        if ( strpos( strtoupper($Bquery), "NOT")!==false )
        {
            $findme   = ' NOT ';
            if (substr($Bquery, 0, 4)=='NOT ')
            {
                $new="-".substr($Bquery, 4);
            }
            else
            {
                $new=str_replace($findme, ' -', $Bquery);
            }
            echo $new;

the search/replace logic is failing because you are urlencoding the string before doing the search/replace, which is changing " " to "+".  Perhaps you meant to urldecode instead? Or perhaps that urlencode needs to happen after this search/replace. 

 

In any case, 

$Bquery = preg_replace('~(?<=\b)(not\s+(?=\w))~i','-',$Bquery);

This will replace "not " with "-" only if there's a word character after it. 

 

Examples:

 

"cat not dog" > "cat -dog"

"not dog" > "-dog"

"cat not" > "cat not"

"cat not " > "cat not "

"cat not ?&$S" > cat not ?&$S"

"cat not 12345" > cat -12345"

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.