Tag Archives: strings

strpos in PHP – like being stung by a needle in a haystack

In PHP when you have a string and want to find out if it contains another string, there are a few ways to do it. You can use regular expressions, use the strstr functions and a few other methods.
The easiest way though is probably by using strpos, which returns the number of the character containing the first occurrence of the thing you’re looking for – and false if the string isn’t found.

Simple – yet with a slight danger.

$haystack = 'This is an example';
if (strpost('This', $haystack)) {
  echo "Found";
} else {
  echo "Not found";
}

In the example above, where we’re looking for the string “This”, the php code will echo “Not found”. The reason is, that the first (and only) occurrence of “This”, is at the begining of the string – character zero.
As strpos returns zero, the if statement is evaluated to false and thus the “Not found” is echoed to the screen.

Fixing the error is simple once you remember the “the first index in a string is zero with strpos” rule:

$haystack = 'This is an example';
if (strpost('This', $haystack) !== false) {
  echo "Found";
} else {
  echo "Not found";
}

Adding the !== false, forces a type check, and as the number zero is (exactly) false, the value echoed is “Found”.

Removing the hash part of an URL

A url may contain a hash/an anchor reference. If you need to remove it from url, it’s quite easy. Here’s a short recipe on how to do it in PHP (including a little test input):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$urls = array(
	'http://example.com/',
	'http://example.com/#test',
	'http://example.com/?id=1',
	'http://example.com/?id=1#test',
	'http://example.com/?id=1&id2=2#test#test',
	'http://example.com/?id=1#test#test'
);
 
foreach ($urls as $url) {
	if (strpos($url, '#')) {
		$url = substr($url, 0, strpos($url, '#'));
	}
	echo $url, "\n";
}

Apart from removing the hash ending from urls, the function can naturally also be used on any number of other similar cases, where you need to trim a string.