1

I have a large text file that i need to remove a certain piece of information from, but i am still learning regular expressions and need some help with the search string statement.

Below is an example of the data i am trying to extract:

"id": "12345"  (good)
"id": "a123"   (bad)

The part i am having trouble with, is that i want to grab the first example, which has ONLY numbers as the value for ID. If there is a letter within the ID, i do not want to grab it. The ID numbers also differ in length, but the format is consistent:

"id": "number_here"

I have the following code but it does not seem to work for what i want to do:

preg_match_all("/\"id\"\:\s\"[0-9]\"/", $input_file) 
1
  • Does this text file have any particular structure? It looks like it could be JSON Commented Apr 30, 2014 at 14:03

2 Answers 2

4

Your regex is good (if a bit heavy on backslashes), except for one fatal flaw: You are only searching for a single digit.

preg_match_all('/"id": "[0-9]+"/', $input_file, $matches);
var_dump($matches);

Hope this helps!

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

2 Comments

worked like a charm! thank you very much!!! I was under the impression that all special chars had to be escaped.
@user3569450 Heh, well there's certainly no harm in escaping things that don't really need it, but it's just a lot more readable to do this ;)
2
  • You don't need to escape many characters in yiur regex
  • Use single quotes for regex
  • Make sure to use quantifier + to match 1 or more digits after "id":

You can use:

preg_match_all('/"id" *: *"[0-9]+"/', $input_string, $matches) ;

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.