w3resource

PHP Regular Expression Exercises: Checks whether a string contains another string

PHP regular expression: Exercise-1 with Solution

Write a PHP script that checks whether a string contains another string.

Visual Presentation:

PHP Regular Expression Exercise: Checks whether a string contains another string

Sample Solution:

PHP Code:

<?php
// Define the regular expression pattern to match 'fox' preceded by a word character and followed by a space
$pattern = '/[^\w]fox\s/';

// Use preg_match function to check if the pattern matches the given string
if (preg_match($pattern, 'The quick brown fox jumps over the lazy dog')) {
    // If 'fox' is found in the string, echo that it is present
    echo "'fox' is present..."."\n";
} else {
    // If 'fox' is not found in the string, echo that it is not present
    echo "'fox' is not present..."."\n";
}
?>

Output:

'fox' is present... 

Explanation:

In the exercise above,

  • A regular expression pattern is defined using the '$pattern' variable. The pattern /[^\w]fox\s/ is used, which matches the word "fox" preceded by a non-word character and followed by a space.
  • The "preg_match()" function checks if the pattern matches the given string 'The quick brown fox jumps over the lazy dog'.
  • If the pattern matches the string, meaning the word "fox" is found as per the defined pattern, it echoes "'fox' is present...".
  • If the pattern doesn't match the string, meaning the word "fox" is not found as per the defined pattern, it echoes "'fox' is not present...".

Flowchart :

Flowchart: Checks whether a string contains another string.

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: PHP Regular Expression Exercises Home.
Next: Write a PHP script that removes the last word from a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php-exercises/php-regular-expression-exercise-1.php