PHP

PHP String Search : Find specific, first or last occurence of some text

Learn how to know whether one string of text is contained within another. PHP gives you several string functions that let you search for one string inside another. We’ll read following PHP string function along with their case-insensitive equivalent where necessary.

strlen function returns characters length in the string

empty function tells whether a variable is empty

substr function returns extracted part of a string

strstr function tells whether the search text is within the string.

strpos and strrpos functions return the index position of the first and last occurrence of the search text, respectively.

substr_count function tells how many times the search text occurs within the string

  1. Find how many characters in a string
  2. How to check if a string is empty
  3. How to extract a part of string
  4. How to extract last character(s) from a string
  5. Format phone numbers
  6. Split each letter in a string
  7. Find if specific character or word exist in the string
  8. Find case-insensitive substring in a string
  9. Find last occurrence of string
  10. Extract file extension from a file name
  11. Extract last directory from path
  12. Searching Strings with strstr
  13. Reverse searching strings with strrchr
  14. How many times some text occurs within a string

Find how many characters in a string

The length of a string is the number of characters in a string. For example, a string of “Brain Bell” has a length of 10, with 9 characters for letters and 1 character for the space.

$length = strlen('Brain Bell');
echo $length;

strlen function returns the length of the given string as show in above example.

How to check if a string is empty

The empty function checks whether the variable is empty, if so, it return true. Variable consider empty if it hasn’t been set, or if the variable contains a NULL value, an empty string (""), or a string of 0.

$var = NULL;
if (empty($var)){
 echo '$var is empty';
}
$var = 0;
if (empty($var)){
 echo '$var is empty';
}
$var = '';
if (empty($var)){
 echo '$var is empty';
}
$var = 'Im not empty';
if (empty($var)){
 echo '$var is empty';
} else {
 echo '$var is not empty';
}

How to extract a part of string

A substring is part of a string. For example, “Brain” is a substring of “Brain Bell“. The substr function returns the portion of a string specified by the start and length (optional) parameters.

Syntax : substr($string, $position, $length)

$string    = 'Brain Bell';
$substring = substr($string, 0, 5);
echo $substring;

Above example prints Brain on the screen. When working with strings, you often need to specify the position of a character within a string. To do that, you use a value of 0 for the first character, 1 for the second character, and so on.

The above example code gets a substring that starts at the first character (position 0) and has a length of five characters. As a result, it returns a value of “Brain“.

$string    = 'Brain Bell';
$substring = substr($string, 6);
echo $substring;

Above code prints Bell on the screen, the length is omitted, so the substr function extracted the substring until the end of the string after the mentioned position 6.

If length not provided. The substr function returns string part after the mentioned position.

How to extract last character(s) from a string

Extracting last four characters:

$string = 'Brain Bell';
$substring = substr($string, -4);
echo $substring;

Above example prints Bell on the screen. We can also specify a negative value for the position parameter to indicate a starting position relative to a string’s end instead of its start.

Format phone number

This example shows how to format a phone number. To start, the first statement stores the phone number as a string that contains numbers with no formatting characters. Then, the next three statements use the substr function to extract the three parts of the phone number. Final statement joins these three parts together.

$phone = 4445556666;

//Extract three characters, from first character at position 0
$first = substr($phone,0,3);

//Extract three characters from fourth character at position 3
$second = substr($phone,3,3);

//Extract all characters from seventh character to the end
$last = substr($phone,6);
echo $first.'-'.$second.'-'.$last;

Split each letter in a string with substr

This example shows how to use a for loop to process each character in a string separately. This loop increments a count from 0 to one less than the length of the string.

Within the loop, the first statement uses the substr function to extract the character at the current position in the string.

$string = 'abcdefghi';
$length = strlen($string);
for ($i = 0; $i < $length; $i++){
 $letter = substr($string, $i ,1);
 echo $letter.'<br>';
}

Split each letter in a string by its index position

To access a character at a particular position, or index , within a string use:

$character = $string[index];

In other words, you place the index between square brackets after the string variable name. String indices start from 0 , so the first character in the string has an index of 0 , the second has an index of 1 , and so on. You can both read and change characters this way.

$string = 'abcdefghij';

//Prints: a
echo $string[0];

//Prints: b
echo $string[1];

//Prints: i
echo $string[8];

/* Print each character in loop */
$length = strlen($string);

for($i=0; $i<$length; $i++){
 echo $string[$i].'<br>';
}

Find if specific character or word exist in the string

We’ll use strpos for finding if a character or word exist in a string. The strpos function return the numeric position of the first occurrence of a character / word in the string.

$string = 'My website name is BrainBell.com';
$txtToFind = 'website';

$pos= strpos($string,$txtToFind);

if ($pos !== false) {

 echo $txtToFind . ' exist at position '. $pos;
 //prints : website exist at position 3

}

Note that the use of !== false is deliberate. strpos returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn’t found. Since 0 is a valid offset and 0 is “falsey”, we can’t use simpler constructs like !strpos($string, $txtToFind).

Find case-insensitive substring in a string

stripos is case-insensitive equivalent of strpos. We’ll use stripos for case-insensitive search to find if a character or word exist in a string.

$string = 'My website name is BrainBell.com';
$txtToFind = 'brainbell';

$pos= stripos($string,$txtToFind);

if ($pos !== false) {

 echo $txtToFind . ' exist at position '. $pos;
 //prints : brainbell exist at position 19
}

Find last occurrence of string

strrpos function return the index position of the last occurrence of the search text.

$string = 'length.file.name.txt';
$txtToFind = '.';

$lastPos= strrpos($string,$txtToFind);

if ($lastPos !== false) {

 echo $txtToFind . ' last occurrence at position '. $lastPos;
 //. last occurrence at position 16

}

Extract file extension from a string

Using substr and strpos functions:

$string = 'length.file.name.txt';
$txtToFind = '.';

$pos = strrpos($string,$txtToFind);

if ($pos !== false) {
 echo substr($string,$pos + 1);
 // prints: txt
}

Using substr and strrchr functions:

$string = 'length.file.name.txt';

$ext = substr(strrchr($string, "."), 1);

Extract last directory from path

//For Windows OS
$path = 'E:\wamp\www\php';
$dir = substr(strrchr($path, "\\"), 1);


//For *nix based OS
$path = '/var/wamp/www/php';
$dir = substr(strrchr($path, "/"), 1);

Searching Strings with strstr

If you just want to find out whether some text occurs within a string, use strstr() . This takes two parameters: the string to search through, and the search text. If the text is found, strstr() returns the portion of the string from the start of the found text to the end of the string. If the text isn’t found, it returns false .

$string = 'Brain Bell!';
$subString = strstr($string, 'Be');
echo $subString;

//Prints : Bell!

You can also pass an optional third argument, the default value is false . If you pass in a value of true, strstr instead returns the portion from the start of the string to the character before the found text.

$string = 'Brain Bell!';
$subString = strstr($string, 'Be', true);
echo $subString;

//Prints : Brain

You can use stristr function for case insensitive strstr.

The strrchr function works similar to strstr function with one difference, it returns the portion of string which starts at the last occurrence.

$string = 'Brain Bell';
$subString = strrchr($string, 'n');
echo $subString;

//Prints : n Bell

How many times some text occurs within a string

Learn how many times a word comes up in a string.

PHP gives you a function to do the job for you: substr_count . To use it, simply pass the string to search and the text to search for, and the function returns the number of times the text was found in the string.

$string = 'red green blue yellow black yellow white';

//Prints : 2
echo substr_count($string, 'yellow');

//Prints : 0
echo substr_count($string, 'orange');

//Prints : 1
echo substr_count($string, 'white');

You can also pass an optional third argument to specify the index position to start searching, and an optional fourth argument to indicate how many characters the function should search before giving up.

$string = 'red green blue yellow black yellow white';
$position = 21;

//Prints : 0
echo substr_count($string, 'blue', $position);

$length = 13;

//Prints : 1
echo substr_count($string, 'yellow', $position, $length);
by BrainBellupdated
Advertisement: