1

I need to search for a string in a string and get the part behind that (without spaces).

Example:

This ABC-Code: 12 3 45
Another ABC-Code: 678 9

Now I'm searching for the keyword ABC-Code: and I want to get the numbers after that (deleting spaces), so the result would be:

12345
6789

I tried to solche that with substr(), but the problem is, that previous characters are variable. So I think I have to use a RegEx, like this:

preg_match("#ABC-Code:(.*?)\n#", $line, $match);
trim($match); // + remove spaces in the middle of the result
user3848987
  • 1,627
  • 1
  • 14
  • 31

3 Answers3

2

You need to use preg_replace_callback function.

$str = <<<EOT
This ABC-Code: 12 3 45
Another ABC-Code: 678 9
EOT;
echo preg_replace_callback('~.*\bABC-Code:(.*)~', function ($m)
        { 
            return str_replace(' ', '', $m[1]);
        }, $str);

Output:

12345
6789
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
1

You can use:

preg_match('#ABC-Code: *([ \d]+)\b#', $line, $match);

And then use:

$num = str_replace(' ', '', $match[1]);
// 12345

for you numbers.

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

You can still do this with substr:

$string = 'This ABC-Code: 12 3 45';
$search = 'ABC-Code:';
$result = str_replace(' ', '', substr($string, strpos($string, $search) + strlen($search)));

But the regex in other answers is certainly prettier :)

rjdown
  • 9,162
  • 3
  • 32
  • 45