Skip to content

Instantly share code, notes, and snippets.

@romulodl
Created December 1, 2011 01:16
Show Gist options
  • Save romulodl/1412498 to your computer and use it in GitHub Desktop.
Save romulodl/1412498 to your computer and use it in GitHub Desktop.
Word Boundary \b php example
<?php
/**
* Example using Word Boundaries (\b)
*/
$regex = "/\b4\b/";
$string = "4, 44, 41, 99, 404, 433, 004, 4";
preg_match_all($regex, $string, $matches);
print_r($matches);
/**
* This will return
* array(
* array(
* 0 => 4,
* 1 => 4
* )
* )
*/
/**
* If you want to replace only the 4's, not the 14's or the 41's
*/
$regex = "/\b4\b/";
$string = "4, 44, 41, 99, 404, 433, 004, 4";
$replacement = 39;
$new_string = preg_replace($regex, $replacement, $string);
echo $new_string;
/**
* This will return
*
* "39, 44, 41, 99, 404, 433, 004, 39";
*
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment