简体   繁体   中英

PHP match specific letters of sentence and get only the words

I'm tiring to write a PHP code for get matched words by using letters, its not the same strpos.

 ex
    $string="How are you robin ?";
    $searchletters="yo";


 in this  "$string" when i search "$searchletters" i need to get 
 the word "you" which have you letters, 

anyone have a idea how to implement this with PHP. Thank You

You can use this regex:

$re = '/\b' . preg_quote($searchletters, '/') . '\w*\b/';

preg_match($re, $string, $m);
echo $m[0] . "\n";
//=> you

RegEx Demo

strtok(strrchr($string,$searchletters), " ");

Explanations:

strrchr() : finds the position of the last occurrence of a string within another string, and returns all characters from this position to the end of the string.

strtok() : which can be used to split a string into smaller strings (tokens) based on some separator(s). For more details and examples, see the strtok PHP manual page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM