1

I want to extract a string out of a string.

I have the following String:

"date-x-days"

I would like to extract the "x", which could be any int value

I already tried this pattern: ~(date-)*(-days)~ But its only giving me "date-" and "-days" back, but I want to receive the number.

How can I do this?

Cheers, Niklas

Fil
  • 8,225
  • 14
  • 59
  • 85
Niklas Riecken
  • 303
  • 1
  • 6
  • 20
  • Why not just `'~\d+~'`? – Wiktor Stribiżew Apr 22 '16 at 10:39
  • You wrote a pseudo pattern of your string and defined what exactly what you want from that string, which is very good! You also tried to do it yourself with the knowledge you have! Now as a next step you can put your regex into here: https://regex101.com/ and check out what exactly your regex currently does. You also can check out this Q&A: http://stackoverflow.com/q/6278296/3933332 and use it to modify your current regex. – Rizier123 Apr 22 '16 at 10:40
  • `sscanf("date-345-days","date-%d-days", $days); echo $days;` – Gordon Apr 22 '16 at 11:27

3 Answers3

2

It can simply done by explode function. try below code

$arr = explode('-','[date-x-days]');
echo $arr[1];
sandeep soni
  • 303
  • 1
  • 12
0
$returnValue = preg_match('/-(\d+)-/', '[date-454-days]', $matches);
print_r($matches);
ssnake
  • 365
  • 2
  • 14
0

With this pattern you will catch each part of the string as a new value, so if you need to edit something you can easily do that.

preg_match("/(date)-(\d+)-(days)/", "date-45-days", $output_array);
echo $output_array[2]; //45

Var_dump(output_array);//= 
array(4
   0    =>  date-35-days
   1    =>  date
   2    =>  35
   3    =>  days
)

See it here: http://www.phpliveregex.com/p/frp as you can see it only catches if all parts are there in order.

Andreas
  • 23,610
  • 6
  • 30
  • 62