Get content that is before the number using regex

Asked

Viewed 107 times

2

$MinhaString = "Aventura, Fantasia, Ação 25 de maio a 31 de maio"

I tried to do it this way, only it doesn’t work.

$Genero = strstr ($MinhaString,"/[^0-9]/",true);

I only need "Adventure, Fantasy, Action". The date is not static.

2 answers

2

You can do this using the preg_match method

preg_match('/^([^0-9]+).*/', "Aventura, Fantasia, Ação 25 de maio a 31 de maio", $matches);
print_r($matches);

A regex '/([ 0-9]+). */' will take all nonnumeral characters before the first number. In your attempt you forgot to put the match in the regex for the rest of the string.

  • I would still put the anchor before the set. More on the subject : http://aurelio.net/regex/guia/ancoras.html#2_3

  • 1

    I changed to include the anchor at the beginning of the string.

  • your regex would already work without the preg_match friend method!

2

This regex will work, it captures all non-numeric content from the beginning of the line to the first occurrence of a digit.

^\D*(?=\d)

Explanation:

  • ^ indicates the start of the line.
  • \D* makes regex capture all non-numeric characters so Greedy.
  • (?=\d) this is a Positive Lookahead with digit, indicates that you should only capture the \D* if there is a digit after the capture group and in that case it already stops the capture.

Trade your Regex for this and it’ll work.

Here’s a test

Browser other questions tagged

You are not signed in. Login or sign up in order to post.