-1

I try to execute a preg_match with PHP but I can not escape the slash properly. The preg_match should return subsrting between Prozessor and first slash

$str="Prozessor: AMD A-Serie A8-4500M / 19 GHz ( 28 GHz ) /";

preg_match('/Prozessor: (.*) \//', $str, $matches)

Prozessor: AMD A-Serie A8-4500M / 19 GHz ( 28 GHz ) /

I would like to get the name of the Processor which should give me back

AMD A-Serie A8-4500M 

What I'm doing wrong

fefe
  • 8,755
  • 27
  • 104
  • 180

3 Answers3

0

Use /Prozessor: (.*?) \//. This will replace a greedy selector with a lazy selector. Example:

$str="Prozessor: AMD A-Serie A8-4500M / 19 GHz ( 28 GHz ) /";
preg_match('/Prozessor: (.*?) \//', $str, $matches);

var_dump($matches[1]);
// string(33) "Prozessor: AMD A-Serie A8-4500M"
Sam
  • 20,096
  • 2
  • 45
  • 71
0

Use a non-greedy quantifier:

preg_match('/Prozessor: (.*?) \//', $str, $matches)

Or a character class:

preg_match('/Prozessor: ([^\/]*) \//', $str, $matches)

Also note, if you change your regex delimiter, you won't have to worry about escaping it:

preg_match('#Prozessor: ([^/]*) /#', $str, $matches)
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
0

This works:

$str="Prozessor: AMD A-Serie A8-4500M / 19 GHz ( 28 GHz ) /";
preg_match('/^Prozessor: (?P<prozessor>[a-z0-9\s-]+) \//i', $str, $matches);
var_dump($matches['prozessor']);

outputs

string(20) "AMD A-Serie A8-4500M"

Or alternatively, you could add an ungreedy modifier to the end of your regex:

preg_match('/Prozessor: (.*) \//U', $str, $matches)

More information here: http://php.net/manual/en/reference.pcre.pattern.modifiers.php

Andris
  • 5,853
  • 3
  • 28
  • 34