1

here is my string

0 12 10 0 5 0 albert 126 al br t 881 alert 58 a lbr t 317 apart 251 al b rt 284 ambit 165 a lb rt 9 album 93 a l br t 881 10 6 13 0 einstein 92 en stein 219 epstein 8 e n stein 335 eastern 62 ens t ein 317 enshrin 13 en st ein 231 enseign 3 ens tei n 203 false albert einstein 154 albert einstein (al br t) einstein 1030 al br t einstein albert (en stein) 318 albert en stein albert epstein 134 albert epstein alert einstein 139 alert einstein

I need to get the value in between false and the number next to the words.. in the above case I require

...false albert einstein 154... => albert einstein

I tried the below regex match, but its not working. What am I missing here?

$matches=array();
preg_match('/false=([a-z]+)\[0-9]+/', $response, $matches);
echo $matches[1];
1
  • Why are you escaping \[ the character class? That will not make the number matching work. And your example text contains spaces that you do not account for. And why does your regex look for a = after the false? Commented Nov 17, 2013 at 3:23

2 Answers 2

3

Try a pattern like this:

false\s*(.+?)\s*[0-9]+

This will match:

  • false - the literal string false
  • \s* - zero or more whitespace characters
  • (.+?) - one or more of any character, non-greedily, captured in group 1
  • \s* - zero or more whitespace characters
  • [0-9]+ - one or more decimal digits

For example:

$input = 'false albert einstein 154';
preg_match('/false\s*(.+?)\s*[0-9]+/', $input, $matches);
echo $matches[1]; // 'albert einstein'
Sign up to request clarification or add additional context in comments.

5 Comments

<some characters><space>false<required text><space><number><some characters> is how the input will be..
@Naren Then you've done something wrong. I've tested this exact code and it works.
@Naren, don't you think providing us the exact input is very important?
I provided the same input, the problem was, I got the content from a server using file_get_contents. When I echoed it and copy pasted it from browser to the code it worked. But it did not when I directly assigned as input string to preg_match.
If it's possible there is a line break between the false and 154 you may need to use the single-line flag (s) -- i.e. /false\s*(.+?)\s*[0-9]+/s
1

The following works for me:

$response = ".false albert einstein 154.";
$matches=array();
preg_match('/.*?false ([a-z\s]+) (?=[0-9]{3}).*/', $response, $matches);
echo $matches[1];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.