Find whole word with strpos()

2019-02-19 20:32发布

Hello people :) I'm trying to use strpos() to find whole words in a sentence. But at the moment, it also find the word if it just are a part of another word. For example:

$mystring = "It's a beautiful morning today!";
$findme   = "a";

$pos = strpos($mystring, $findme);

In this example it would find "a" in the word "a" (as it should do), but also in "beautiful" because there is an a in it.

How can i find only whole words and not if it is a part of other words?

标签: php strpos
3条回答
一纸荒年 Trace。
2楼-- · 2019-02-19 20:43

Use regex , with the word boundary delimiter \b, like this :

$mystring = "It's a beautiful morning today!";
preg_match_all('/\ba\b/', $mystring, $matches, PREG_OFFSET_CAPTURE);
var_dump($matches);

returns

array(1) {
  [0]=>
  array(1) {
    [0]=>
    array(2) {
      [0]=>
      string(1) "a"
      [1]=>
      int(5)
    }
  }
}
查看更多
等我变得足够好
3楼-- · 2019-02-19 20:49

regex is hard for beginners, another way and I admit it isn't the best, would be to use
$findme = " a "

查看更多
乱世女痞
4楼-- · 2019-02-19 20:59

This is a job for regex:

$regex = '/\b'.$word.'\b/';

Basically, it's finding the letters surrounded by a word-boundary (the \b bits). So, to find the position:

preg_match($regex, $string, $match, PREG_OFFSET_CAPTURE);
$pos = $match[0][1];
查看更多
登录 后发表回答