开发者

php removing part of string

Why does this not remove the http:// of the st开发者_JAVA技巧ring?

$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) {


Change if($httpposi === true) { to if($httpposi) { or if($httpposi == true) {, since $httpposi = 4 isn't === to true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜