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;
?>
Link to comment
Share on other sites

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;
Link to comment
Share on other sites

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"

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.