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.

Pictorial Presentation:

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

Sample Solution:

PHP Code:

<?php
$pattern = '/[^\w]fox\s/';
if (preg_match($pattern, 'The quick brown fox jumps over the lazy dog'))
  {
  echo "'fox' is present..."."\n";
  }
  else
  echo "'fox' is not present..."."\n";
?>

Sample Output:

'fox' is 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?



PHP: Tips of the Day

Getting all defined constants

To get all defined constants including those created by PHP use the get_defined_constants function:

Example:

<?php
$constants = get_defined_constants();
var_dump($constants); // pretty large list

Output:

array(2250) {
  ["E_ERROR"]=>
  int(1)
  ["E_RECOVERABLE_ERROR"]=>
  int(4096)
  ["E_WARNING"]=>
  .....
  .....
  resource(1) of type (stream)
  ["STDOUT"]=>
  resource(2) of type (stream)
  ["STDERR"]=>
  resource(3) of type (stream)
}

To get only those constants that were defined by your app call the function at the beginning and at the end of your script (normally after the bootstrap process):

<?php
$constants = get_defined_constants();
define("HELLO", "hello");
define("WORLD", "world");
$new_constants = get_defined_constants();
$myconstants = array_diff_assoc($new_constants, $constants);
var_export($myconstants);

Output:

array (
  'HELLO' => 'hello',
  'WORLD' => 'world',
)

It's sometimes useful for debugging