Last active
October 27, 2018 23:59
-
-
Save alexrusin/115a928d4c991f723881c29c44858296 to your computer and use it in GitHub Desktop.
RegEx practice
This file contains 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 | |
$string = "This website is stupid. Your speaking style is idiotic. Your knowledge is crap.This is so stupid. You are an idiot. You are an IDIOT!"; | |
echo preg_replace('/stupid|idiot(?:ic)?|crap/i', 'amazing', $string) . PHP_EOL . PHP_EOL; | |
$website1 = 'www.laracasts.com'; | |
$website2 = 'alexrusin.com'; | |
echo preg_replace('/www\.([^\.]+)/i', '$1', $website1) . PHP_EOL; | |
echo preg_replace('/www\.([^\.]+)/i', '$1', $website2) . PHP_EOL . PHP_EOL; | |
$phrase = 'Thanks for help, @JohnDoe. | |
@JohnDoe, thanks for the help! | |
@JonDoe rocks!'; | |
echo preg_replace('/@(\w+)/i', '<a href="https://google.com/$1">@$1</a>', $phrase) . PHP_EOL . PHP_EOL; | |
// (?=string) | |
// (?!string) | |
$lookAhead = '<a href="http://google.com">Google</a> | |
google.com is the best search engine.'; | |
echo preg_replace('/google(?=<)/i', 'Change', $lookAhead) . PHP_EOL; | |
echo preg_replace('/google(?!<)/i', 'Change', $lookAhead) . PHP_EOL . PHP_EOL; | |
// (?<=string) | |
// (?<!string) | |
$lookBehind = '$name = "Quaid"; My name is Quaid'; | |
echo preg_replace('/(?<=\$)name/i', 'VARIABLE', $lookBehind) . PHP_EOL; | |
echo preg_replace('/(?<!\$)name/i', 'VARIABLE', $lookBehind) . PHP_EOL . PHP_EOL; | |
$message = "Listen, Centari, I'm not any of those guys. I'm a kid from a trailer park. Okay, centauri?"; | |
if (stristr($message, 'Centauri')) { | |
var_dump('We found it'); | |
} | |
if (preg_match('/Centau?ri/i', $message)) { | |
var_dump('We found it'); | |
} | |
preg_match('/Centau?ri/i', $message, $matches); | |
var_dump($matches); | |
preg_match_all('/Centau?ri/i', $message, $matches); | |
var_dump($matches); | |
var_dump(preg_replace('/Centau?ri/i', 'John', $message)); | |
$message = " foo , bar, baz "; | |
$message = trim($message); | |
$array = preg_split('/\s*,\s*/', $message); | |
var_dump($array); | |
$comments = [ | |
"Always trust Centauri.", | |
"You almost got me killed.", | |
"You are the man, dog.", | |
"Listen, Centari. I'm not any of those guys, I'm a kid from trailer park." | |
]; | |
$filtered = array_filter($comments, function($comment){ | |
return preg_match('/Centau?ri/i', $comment); | |
}); | |
var_dump($filtered); | |
$filtered = preg_grep('/Centau?ri/i', $comments); | |
var_dump($filtered); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment