简体   繁体   中英

php removing part of string

Why does this not remove the http:// of the string?

$rurl = 'http://www.google.com';
$httpposi = strpos($rurl,'://');
echo $httpposi;
if($httpposi === true) {
$url=substr($rurl, strpos($rurl, '://') + 3);
echo $url;
} else {
$url=$rurl;
echo '3'.$url.'2';
}

echo $url;

Instead of:

if($httpposi === true) {

you need:

if($httpposi !== false) {

since if it is found in the string, it will return an offset as an integer, and you are doing a strict comparison and strictly an non-zero, positive integer is not equal to the boolean value true .

8 == true // true
8 === true // false, because 8 is not a boolean
0 == true // false, but we need to know if the needle is at position 0

so:

0 !== false // true, string was found
8 !== false // true, string was found
false !== false // false, string was not found

If the sequence is found at the beginning of the string, the falsy 0 will be returned, thus the need to strictly compare to false to know that it has not been found at all.

http://ideone.com/QXBs7

As a few others already posted: Do not compare $httpposi with a boolean value! The return value of the strpos function is an integer value if it has found an occurence, but can return either false , 0 or "" if it didn't find your passed string.

For more information, take a look at the PHP.net docs !

Or you could use preg_replace instead and get rid of the problem another way:

$url=preg_replace('~^https?://~i','','http://www.google.com')

Caters for https as well. Just remove [s]? if that's not what you want. The /i is for ignoring case.

if($httpposi !== false) {
\n

if($httpposi === true) {更改为if($httpposi) {if($httpposi == true) { ,因为$httpposi = 4不是===true

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