1

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?

2 Answers 2

6

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:]]+/
Sign up to request clarification or add additional context in comments.

2 Comments

Capturing group is not needed here. It only matches what is needed.
Thank you. This is working like charm. As input can also cointain results like ´number_space_'-'_space_number´ I've removed all spaces from every input.
1

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);

?>

1 Comment

/i is not needed here. Digits has no case-sensivity

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.