0

I'm trying to use regex to get rid of the first and last word in a sentence, but it only works when I'm using spaces to match, but it doesn't work when I'm trying to use word boundary. Why is that?

Using Spaces:

$inputX = "she hates my guts";
preg_match("~ .+ ~i", $inputX, $match);

print_r($match);

Result:

Array ( [0] => hates my )

Using Word Boundary:

$inputX = "she hates my guts";
preg_match("~\b.+\b~i", $inputX, $match);

print_r($match);

Result:

Array ( [0] => she hates my guts )
5
  • The . is greedy so .+? but then the result is she because start of string is a boundary. Commented Nov 5, 2015 at 22:16
  • 2
    \b is before she and after guts as well. Commented Nov 5, 2015 at 22:17
  • @anubhava: Yes, but it's not preg_match_all() so only she. Commented Nov 5, 2015 at 22:17
  • 1
    why do you want to use word boundaries when you have a working regex with spaces? as @anubhava mentioned, \b will also match positions in the first and last word Commented Nov 5, 2015 at 22:27
  • By default, engines think of the beginning and end of string as a NON-word. Commented Nov 5, 2015 at 22:40

2 Answers 2

1

Here are the word boundaries:

 s h e   h a t e s   m y   g u t s 
^     ^ ^         ^ ^   ^ ^       ^

So your pattern matches like this:

 s h e   h a t e s   m y   g u t s 
^\_______________________________/^
|               |                 |
\b              .+                \b

If you want to get rid of the first and last word, I'd just replace these with an empty string, using the following pattern:

^\W*?\w+\s*|\s*\w+\W*$

Both \W* are there to account for possible punctuation (ie she hates my guts.) but you can remove them if they're not needed.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey, nice letter graphics!
0

If you want to remove the first and last word in a sentence, you can:

  1. explode() on spaces
  2. remove the first and last element with array_slice()
  3. implode() back again

Code

$inputX = "she hates my guts";
$result = implode(" ", array_slice(explode(" ", $inputX), 1, -1));

var_dump($result);

Output

string(8) "hates my"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.