John Svensson
John Svensson

Reputation: 461

Regex match string words

I have the following:

<?php

$searchExpression = 'hello there yo\'s -3 "hey"';

preg_match_all("/\"([^\]]*)\"/", $searchExpression, $exact_words);

var_dump($exact_words[1]);

echo '<br><br>';

preg_match_all("/(-\d+)/", $searchExpression, $blabla);

var_dump($blabla[1]);

These matches

-3
"hey"

How can I match the other words "hello", "there", "yo's"? These can be any string word.

Upvotes: 1

Views: 54

Answers (2)

Rohan Khude
Rohan Khude

Reputation: 4913

You could use explode, split or preg_split.

explode uses a fixed string:

$parts = explode(' ', $string);

while split and preg_split use a regular expression:

$parts = split(' +', $string);
$parts = preg_split('/ +/', $string);

An example where the regular expression based splitting is useful:

$string = 'hello there yo\'s -3 "hey"';
var_dump(explode(' ', $string));
var_dump(split(' +', $string));
var_dump(preg_split('/ +/', $string));

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

You can use the following technique: match what you do not want to return and fail the match manually with (*SKIP)(*F) verbs, and then match whatever you need.

Here is a sample regex:

(?:-\d+|"[^"]*")(*SKIP)(*F)|\S+

See demo

The (?:-\d+|"[^"]*") will be skipped and \S+ will match all sequences of non-whitespace characters.

IDEONE Demo:

$re = '/(?:-\d+|"[^"]*")(*SKIP)(*F)|\S+/'; 
$str = "hello there yo\'s -3 \"hey\""; 
preg_match_all($re, $str, $matches);
print_r($matches);

Upvotes: 1

Related Questions