Regex, PHP - finding words that need correction -
i have long string words. of words have special letters.
for example string "have rea$l problem with$ dolar inp$t" , have special letter "$".
i need find , return words special letters in quickest way possible.
what did function parse string space , using “for” going on words , searching special character in each word. when finds it—it saves in array. have been told using regexes can have better performance , don’t know how implement using them.
what best approach it?
i new regex understand can me task?
my code: (forbiden const) code works now, 1 forbidden char.
function findspecialchar($x){ $special = ""; $exploded = explode(" ", $x); foreach ($exploded $word){ if (strpos($word,$forbidden) !== false) $special .= $word; } return $special; }
you use preg_match
this:
// set special word here. $special_word = "café"; // set sentence here. $string = "i eat food @ café , read magazine."; // run through 'preg_match''. preg_match("/(?:\w|^)(\q$special_word\e)(?:\w|$)/i", $string, $matches); // dump results see working. echo '<pre>'; print_r($matches); echo '</pre>';
the output be:
array ( [0] => café [1] => café )
then if wanted replace that, using preg_replace
:
// set special word here. $special_word = "café"; // set special word here. $special_word_replacement = " restaurant "; // set sentence here. $string = "i eat food @ café , read magazine."; // run through 'preg_replace''. $new_string = preg_replace("/(?:\w|^)(\q$special_word\e)(?:\w|$)/i", $special_word_replacement, $string); // echo results. echo $new_string;
and output be:
i eat food @ restaurant , read magazine.
i sure regex refined avoid having add spaces before , after " restaurant "
in example, basic concept believe looking for.
Comments
Post a Comment