RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.69% (5.89%*) • Home Loan Fixed: 5.59% (5.85%*) • Fixed: 5.59% (5.85%*) • Variable: 5.69% (5.89%*) • Investment IO: 5.79% (6.41%*) • Investment PI: 5.79% (6.21%*)

Find a String in a String with PHP

Find a String in a String with PHP

This article will provide you with a few functions that serve one very commonly asked PHP question: how can I find if there's an occurrence of a string in another string. We'll provide just a couple of examples, although there's countless ways in which it can be accomplished.

String Functions

stripos will find the numeric position of the last occurrence of needle in the haystack (case-insensitive) string (or last occurrence of a substring in a string). The Boolean result is intended to work with a case-insensitive 'search' although it's easy to alter for case-sensitivity with the use of strpos() .

So, to check for $word = 'Aquarius' in $string = "This is the age of Aquarius", we would use the following. It will return 'Match found'.

1
<?php 
2
echo (stripos($string, $word) !== false) ? 'Match found' : 'Match not found';

Writing a wrapper for a function is normally a little bizarre... except we've changed the requirements a few times for an application we worked on, and had to occasionally alter the way in which data was matched. The considerations at the bottom of the page might give you an indication of why we've altered a default function. The following is just an example:

1
<?php 
2
/*
3
 Find a String in a String with PHP
4
 http://www.beliefmedia.com/find-string-php
5
 http://php.net/manual/en/function.stripos.php
6
*/
7
 
8
function beliefmedia_stringpos($string, $word, $offset = '0', $cs = true) {
9
  $string_position = ($cs) ? 'strrpos' : 'strripos';
10
 
11
  /* Stop throwing errors by truncating offset to strlen($string) */
12
  $string_length = strlen($string);
13
  $sign = (($offset > 0) - ($offset < 0));
14
  $sign = ($sign = -1) ? '-' : '+';
15
 
16
  if (abs($offset) > $string_length) $offset = $sign . $string_length;
17
 return ($string_position($string, $word, $offset) !== false) ? true : false;
18
}

Example Usage

1
<?php 
2
/* Usage */
3
$word = ' Aquarius';
4
$string = "This is the age of Aquarius";
5
echo (beliefmedia_stringpos($string, $word) !== false) ? 'Match found' : 'Match not found';

The example usage returns true. It will also return true for a partial... so searching for 'cat' will also return true if the word 'cats' is in the string (the functions will also match spaces so this is often a ways of navigating this issue).

If $offset is specified, the search will start this number of characters counted from the beginning of the string. If the offset is negative, the search will start this number of characters counted from the end of the string.

Preg_Match() Function

PHP's preg_match searches a subject for a match to the regular expression given in pattern. While using a regular expression might cost you a few seconds of processing power over the course of its lifetime, it sometimes yields a better result - particularly if you don't want to match a partial.

1
<?php 
2
/*
3
 Find a String in a String with PHP
4
 http://www.beliefmedia.com/find-string-php
5
 http://php.net/manual/en/function.preg-match.php
6
*/
7
 
8
function beliefmedia_find_string($word, $string) {
9
 return (preg_match(&quot;/\b$word\b/i&quot;, &quot;$string&quot;)) ? true : false;
10
}
11
 
12
/* Usage */
13
$word = 'Aquarius';
14
$string = &quot;This is the age of Aquarius&quot;;
15
echo (beliefmedia_find_string($word, $string) !== false) ? 'Match found' : 'Match not found';

Our example usage will return true. Unlike the former function, this function won't return a partial match as true. The "i" after the pattern delimiter indicates a case-insensitive search. Remove for case-sensitivity.

Unlike the PHP functions above, there's no offset... although you could use other means to return a partial string.

Considerations

  • The str[i]pos() functions were what we traditionally used as a check, however they didn't provide a negative $offset argument until PHP 7 (earlier versions will throw an error). The function finds the position of the first occurrence of a substring in a string. If the $offset is negative, the search will start this number of characters counted from the end of the string, and search forwards (returning the integer value of the first occurrence).
  • The strr[i]pos() (note the extra 'r') functions provided for a negative $offset argument prior to PHP 7. The function finds the position of the last occurrence of a substring in a string. If the value of the $offset is negative, search will instead start from that many characters from the end of the string, searching backwards (returning the integer value of the last occurrence).
  • If strr[i]pos() uses a negative offset, the function need only match part of your $needle to return true.
  • If the offset is greater than the haystack the function will throw an error: strrpos(): Offset is greater than the length of haystack string in * on line *. For this reason, we'll truncate the length of the $offset to the length of the string. That said, it alters expected behaviour so shouldn't be used in this way if it's going to cause problems.

These functions are some that have always bothered me... while it's usually only the $offset use that causes potential problems. Keep in mind that while we've used our functions to test for true or false, the intention of all the string functions are to provide an index for the $string position in the $haystack.

Download


Title: Find a String in a String with PHP
Description: Find an occurrence of a string in another string. A few sample functions. Far from best practice.
  Download • Version 0.2, 691.0B, zip, Category: PHP Code & Snippets

■ ■ ■

 
Download our complimentary 650-page guide on marketing for mortgage brokers. We'll show you exactly how we generate billions in volume for our clients.
Finance Guide, Cropped Top and Bottom
  Timezone: 1 · [ CHANGE ]

RELATED READING

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment