Created
December 1, 2011 01:16
-
-
Save romulodl/1412498 to your computer and use it in GitHub Desktop.
Word Boundary \b php example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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