1 / 3
Caption Text
2 / 3
Caption Two
3 / 3
Caption Three margin testing

Monday, February 1, 2010

How to check if string contains substring in PHP

How to check if string contains substring PHP

if $_SERVER['REQUEST_URI'] already contains a ? then using & instead
$HL_lnk = strpos($_SERVER['REQUEST_URI'],'?')?'&':'?';

------

Often, we see two approaches for this.

Option 1

One option is to use the strpos PHP function. The following example shows how this is used:

<?php
$pos = strpos($haystack,$needle);

if($pos === false) {
// string needle NOT found in haystack
}
else {
// string needle found in haystack
}
?>

Watch out, checking for substring inside string in PHP can be tricky. Some people do just something like

if ($pos > 0) {}

or perhaps something like

if (strpos($haystack,$needle)) {
// We found a string inside string
}

and forget that the $needle string can be right at the beginning of the $haystack, at position zero. The

if (strpos($haystack,$needle)) { }

code does not produce the same result as the first set of code shown above and would fail if we were looking for example for "moth" in the word "mother".

Option 2

Another option is to use the strstr() function. A code like the following could be used:

if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}

Note, the strstr() function is case-sensitive. For a case-insensitive search, use the stristr() function.

Which is Better?

The strpos() function approach is a better way to find out whether a string contains substring PHP because it is much faster and less memory intensive.

Any Word of Caution?

If possible, it is a good idea to wrap both $haystack and $needle with the strtolower() function. This function converts your strings into lower case which helps to eliminate problems with case sensitivity.

Firebug vs. Web Developer: Debug and tune apps on the fly

LXer: Firebug vs. Web Developer: Debug and tune apps on the fly with Firebug

(After upgrade to Firefox 3.6, I installed Firebug 1.5.0 and Google Speed 1.6.0. HL 20100201 )

We use these a lot in my shop, and there's a schism of sorts between the Firebug and Web Developer extensions.

I've used both, but haven't gotten too deep into either one. Right now I have Web Developer 1.1.5 running. It's a bit less "invasive" than Firebug, but I'm not saying I won't go back and try the other one.

I run both at the same time, but usually keep firebug disabled unless I actually use it. Both have features the other lacks.

Featured Post

Windows和Ubuntu双系统完全独立的安装方法

http://www.ubuntuhome.com/windows-and-ubuntu-install.html  | Ubuntu Home Posted by Snow on 2012/06/25 安装Windows和Ubuntu双系统时,很多人喜欢先安装windows,然...