0

Say I have this string: fg_^"-kv:("value_i_want")frt. That string will stay constant except for value_i_want - which could change all the time. This little string is hidden within a huge string of data (constantly changing), I have saved in a PHP variable

Is there any I could do a Regular Expression on a string, let's say of 50000 characters to find that string (above) without knowing what the value_i_want is, and then saving the value in a variable - using PHP

3
  • 3
    the size limit of searching through a string is only limited by the amount of memory your php installation has access to. You could do this pretty easy with something like: /fg_\^"\-kv:\("(.*?)"\)frt/s. Commented Feb 9, 2015 at 18:40
  • you want to say? this fg_^"-kv:("......")frt is a sub string of a 5000 word paragraph? Commented Feb 9, 2015 at 18:41
  • 2
    If the stuff on the outside is always constant, you can just use substr. Commented Feb 9, 2015 at 18:42

2 Answers 2

3

You can just use strpos to find where the value you want is. You may need to tweak this a little, I haven't tested it. $long_string is the string you are searching for a match in.

$start = strpos($long_string, 'fg_^"-kv:("', 0);
$end = strpos($long_string, '")frt', $start);
$value_i_want = substr($long_string, $start+11, $end-$start-11);
Sign up to request clarification or add additional context in comments.

2 Comments

If the string is a constant, strpos usage is preferrable since it's way faster than preg_* functions.
strpos() doesn't seem to work when the string I'm looking for has quotation marks in it
1

Try this:

if (preg_match_all('/(?<=fg_\^\"\-kv:\(\")[a-z_]+(?=\"\)frt)/', $yourstring, $matches)) {
  echo "Match was found <br />";
  echo $matches[0];
}

Pattern: (?<=fg_\^\"\-kv:\(\")[a-z_]+(?=\"\)frt)

(?<=fg_\^\"\-kv:\(\") - positive lookbehind assertion, means that searched string should be after exactly this string: fg_^"-kv:("

(?=\"\)frt) - positive lookahead assertion, means the same, but before: ")frt

[a-z_]+ - the string you are looking for, may consist of one or more letter and underscores. Change it for your needs.

Demo: https://regex101.com/r/vS7dI0/1

1 Comment

The g modifier doesn't exist in PHP (when you want to find several occurences, you need to use preg_match_all). The m modifier is not needed since you don't use anchors. You should use single quotes for the regex string instead of escaping all the double quotes. No need to escape the hyphen outside a character class. You write "Change it for your needs" but what happens if there is no particular constraint on characters?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.