Reinherd
Reinherd

Reputation: 5506

Replacing string with regex

I'm trying to extract from a string like this:

$message = #porrabarça per avui @RTorq el  @FCBar guanyarà per 3-1 al AC Milan

The '3-1'. As Number - Number

I've tried

$message = preg_replace('/[0-9]\s*-\s[0-9]/i', '', $message);

But it isnt working. It's output is the same as the input.

Can you help me out?

Upvotes: 1

Views: 63

Answers (2)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57640

The problem is \s here.

/[0-9]\s*-\s[0-9]/
           ^
           |
           +--- This makes a single space mandatory. 

You need \s* there. Use preg_match to extract anything. preg_match matches and optionally set the match to a variable. From there you can extract the matches. preg_replace replaces the matched content.

preg_match("/\d+\s*-\s*\d+/", $message, $match);
$num = $match[0];

http://ideone.com/BWKZQV

To replace use this pattern and empty string as replace string in preg_replace.

A better pattern would using POSIX character classes. it'll match any type digit characters of any other locale.

/[[:digit:]]+[[:space:]]*-[[:space:]]*[[:digit:]]+/

Upvotes: 6

Prasanth Bendra
Prasanth Bendra

Reputation: 32710

If you want to replace the string :

<?php  
$message="#porrabarça per avui @RTorq el  @FCBar guanyarà per 3-1 al AC Milan";

echo $message = preg_replace('/[0-9]+-[0-9]+/', '', $message);

?>

If you want to get matched groups :

<?php  
$message="#porrabarça per avui @RTorq el  @FCBar guanyarà per 3-1 al AC Milan";

preg_match_all('/[0-9]+-[0-9]+/', $message, $matches);

print_r($matches);

?>

Upvotes: 1

Related Questions