Word matching in php

PHP Regular Expressions

A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace operations.

Syntax

In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers.

In the example above, / is the delimiter, w3schools is the pattern that is being searched for, and i is a modifier that makes the search case-insensitive.

The delimiter can be any character that is not a letter, number, backslash or space. The most common delimiter is the forward slash (/), but when your pattern contains forward slashes it is convenient to choose other delimiters such as # or ~.

Regular Expression Functions

PHP provides a variety of functions that allow you to use regular expressions. The preg_match() , preg_match_all() and preg_replace() functions are some of the most commonly used ones:

Function Description
preg_match() Returns 1 if the pattern was found in the string and 0 if not
preg_match_all() Returns the number of times the pattern was found in the string, which may also be 0
preg_replace() Returns a new string where matched patterns have been replaced with another string

Using preg_match()

The preg_match() function will tell you whether a string contains matches of a pattern.

Example

Use a regular expression to do a case-insensitive search for «w3schools» in a string:

Using preg_match_all()

The preg_match_all() function will tell you how many matches were found for a pattern in a string.

Example

Use a regular expression to do a case-insensitive count of the number of occurrences of «ain» in a string:

$str = «The rain in SPAIN falls mainly on the plains.»;
$pattern = «/ain/i»;
echo preg_match_all($pattern, $str); // Outputs 4
?>

Читайте также:  Java android string contains

Using preg_replace()

The preg_replace() function will replace all of the matches of the pattern in a string with another string.

Example

Use a case-insensitive regular expression to replace Microsoft with W3Schools in a string:

$str = «Visit Microsoft!»;
$pattern = «/microsoft/i»;
echo preg_replace($pattern, «W3Schools», $str); // Outputs «Visit W3Schools!»
?>

Regular Expression Modifiers

Modifiers can change how a search is performed.

Modifier Description
i Performs a case-insensitive search
m Performs a multiline search (patterns that search for the beginning or end of a string will match the beginning or end of each line)
u Enables correct matching of UTF-8 encoded patterns

Regular Expression Patterns

Brackets are used to find a range of characters:

Expression Description
[abc] Find one character from the options between the brackets
[^abc] Find any character NOT between the brackets
4 Find one character from the range 0 to 9

Metacharacters

Metacharacters are characters with a special meaning:

Metacharacter Description
| Find a match for any one of the patterns separated by | as in: cat|dog|fish
. Find just one instance of any character
^ Finds a match as the beginning of a string as in: ^Hello
$ Finds a match at the end of the string as in: World$
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers

Quantifiers define quantities:

Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n Matches any string that contains a sequence of X n‘s
n Matches any string that contains a sequence of X to Y n‘s
n Matches any string that contains a sequence of at least X n‘s

Note: If your expression needs to search for one of the special characters you can use a backslash ( \ ) to escape them. For example, to search for one or more question marks you can use the following expression: $pattern = ‘/\?+/’;

Grouping

You can use parentheses ( ) to apply quantifiers to entire patterns. They also can be used to select parts of the pattern to be used as a match.

Example

Use grouping to search for the word «banana» by looking for ba followed by two instances of na:

Complete RegExp Reference

The reference contains descriptions and examples of all Regular Expression functions.

Источник

String contains multiple words

There are several ways to determine if a given string contains a specific word in PHP. It depends on the program context we are solving.

As we are here to check that a PHP string contains multiple words, therefore, assuming that you are already aware of a single word search within the string. Therefore first we will see how to check if a string contains any word in short.

One of the best ways to check single word using PHP function strpos

$searchText = «QuizCure»; $givenString = «Programming articles listed on QuizCure belongs to java, python, PHP and more»; if(strpos($givenString, $searchText) !== false) < echo "QuizCure text Found!"; >else

Result: QuizCure text Found!

Explanation:

  • strpos is used to check the position of the first existence of a search word
  • strpos is case-sensitive. Therefore it will match the same case letters only.
  • In our example above we have searchText as QuizCure and the given string also contains the same set of upper and lowercase combinations of word QuizCure.
  • strpos($givenString, $searchText) return false if it doesn’t find the searchText position in the given string. Therefore I used criteria strpos($givenString, $searchText) !== false to test.

Now let’s explore how can we check string containing more than one word in a given string in the following ways

Scroll for More Useful Information and Relevant FAQs

Источник

Check If A String Contains A Specific Word In PHP

check if a string contains a specific word in php

Often, developers want to check string contains a specific word or not in PHP. For that, we can use strpos() and preg_match() functions to do that. Let’s see how to do it.

Check If a String Contains a Specific Word

01 Find Exact Match Using the PHP preg_match() Function

You can use the PHP preg_match() function to check whether a text contains a specific word or not.

Use: The preg_match() function is used to find the exact match of a pattern in a string of text using a regular expression search.

Return: This function will return true if the pattern is matched otherwise it will return false .

The following example will check for the exact match of the word like we are searching for aware then it will only search for the aware word and not a partial word like «beware», «unaware», «awareness», etc.

The \b expression in the pattern specify a word boundary.

Case Insensitive Search with preg_match()

For case-insensitive search put the «i» after the pattern delimiter as shown below:

In the above example, we are checking for aware specific word but our string contains a capital AWARE but although it will return A match was found . due to case-insensitive searches.

02 Use the PHP strpos() Function

You can also use the PHP’s strpos() function to check whether a string contains a specific word or not.

The strpos() function will return the position of the first occurrence of a substring in a string. It will return false if the match not found.

Please note that strpos() start searching from 0 index so use strict comparision operator using === or !== otherwise it will considered 0 = false .

Let’s see the example for better understanding:

You can also check if the string contains a word or not by using other PHP functions like stripos(), strstr(), stristr(), substr_count(), mb_strpos(), etc.

Why to Use preg_match() And Not strpos()

The preg_match() is better for word matching in comparison to strpos() because if you are checking the string contains a word like «are» and if your string contains words like careful, beware, prepare, etc. then strpos() will also return true.

To understand this situation please considered the below example:

The above example should return the false , but it’s returning true as output.

That’s it for now. We hope this article helped you to check if a string contains a specific word in PHP.

Additionally, read our guide:

  1. Best Way to Remove Public from URL in Laravel
  2. Error After php artisan config:cache In Laravel
  3. Specified Key Was Too Long Error In Laravel
  4. Active Directory Using LDAP in PHP or Laravel
  5. How To Use The Laravel Soft Delete
  6. How To Add Laravel Next Prev Pagination
  7. cURL error 60: SSL certificate problem: unable to get local issuer certificate
  8. Difference Between Factory And Seeders In Laravel
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Calculate Age From Birthdate
  11. How To Find Duplicate Records in Database

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂. Keep Smiling! Happy Coding!

Источник

Оцените статью