-1

I have the following string:

feature name="osp"

I need to extract part of the strings out and put them into a new string. The word feature can change and the word inside quotes can change so I need to be able to capture any instance possible. The name=" " part is always the same. The result I need is:

feature osp

I need to filter out the name= and quotes from the string.

I've used this ^\w*\s to get the first feature part but can't figure out how to extract osp from the string using a regex. I've been looking here RegEx: Grabbing values between quotation marks but can't get a regex that combines both to get the result I need. I'm working in PHP so using preg-match at the moment. Can anyone help with this?

Community
  • 1
  • 1
olliejjc16
  • 361
  • 5
  • 20

3 Answers3

3

I'd go with

(\w+)\s+name\s*=\s*"([^"]*)

It's a little bit slower, but it allows for arbitrary number of spaces and it captures the first word correctly, even with Alexandru's test.

See it work here at regex101.

Regards

SamWhan
  • 8,296
  • 1
  • 18
  • 45
  • Thanks to everyone who answered all three answers below seem to work, this seems to be the most suitable answer for what I'm looking for thanks for the help! – olliejjc16 Apr 28 '16 at 09:02
1

Try something like that:

preg_match('/(.+)name="(.+?)"/', $string, $matches);

echo $matches[1] . $matches[2];
vuryss
  • 1,270
  • 8
  • 16
  • (.+) Will capture all the string you should go for the lazy `?` – Alexandru Olaru Apr 28 '16 at 08:36
  • Try this test `feature name fasfjah fjkhas kfhajk hkask name="test" feature name="test"` – Alexandru Olaru Apr 28 '16 at 08:39
  • 1
    This is not his example case. – vuryss Apr 28 '16 at 08:40
  • 1
    Why are people on here always making up strings and cases that are unreal just to make an answer not work? The OP clearly wrote how the case and how it needed to function and yet someone (@AlexandruOlaru) comes up with something that is not part of the problem. I will upvote your answe vuryss just to make a statement agains people like Alexandru! – Andreas Apr 28 '16 at 08:57
0

An improved version of @vuryss

preg_match('/(.*?)name="(.*?)"/ims', $string, $matches);    
echo $matches[1] . $matches[2];
Alexandru Olaru
  • 6,842
  • 6
  • 27
  • 53