简体   繁体   中英

strpos function doesn't detect instance if it's first word in a string

Need to substitute piece of string with values coming from url parameter. Created a {{hkw}} "token" for that. Works perfectly fine if substituted text is not used as a first thing in a string. But if I use it in a very beginning- nothing happens. For example: If I use "Substitute fullowing {{hkw}}", everything gets substituted properly. If I use "{{hkw}} Should be substituted", nothing happens and {{hkw}} is still there.

At first, I tried this

     if (strpos($kwttl,'{{hkw}}') !== false)

After googling, I found that following should work

    if (strpos($kwttl,'{{hkw}}') === true)

But it didn't. Here is my full code.

    $fullurl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    $kwttl = get_the_title();
    if (strpos($fullurl,'hkw') === true) {
        $hkwsub = $_GET['hkw'];
        if (strpos($hkwsub,'+') === true) {
            $hkwsub = str_replace('+', ' ', $hkwsub);
        } 
    } else {
        $hkwsub = '';
    }
    if (strpos($kwttl,'{{hkw}}')) {
        $kwttl = str_replace('{{hkw}}', $hkwsub, $kwttl);
    }

error log is empty

Your assumption that strpos() can return strict true is incorrect. The function strpos() returns either:

  1. false if the string is not found, or
  2. An integer >= 0 if the string is found

PHP Manual Reference

Your full code should instead be this:

$fullurl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$kwttl = get_the_title();
if (strpos($fullurl,'hkw') !== false) {
    $hkwsub = $_GET['hkw'];
    if (strpos($hkwsub,'+') !== false) {
        $hkwsub = str_replace('+', ' ', $hkwsub);
    } 
} else {
    $hkwsub = '';
}
if (strpos($kwttl,'{{hkw}}') !== false) {
    $kwttl = str_replace('{{hkw}}', $hkwsub, $kwttl);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM