The best regular expression for these strings?

Jack n Jill asked
php regex preg-replace
via

I’m learning regular expression and the tutor gave me this advanced exercise.

Use preg_replace and create a regex that can remove all of numbers at the beginning of the following strings.

01. A little love (2002)
02 - No.1 Star
03 Love Story

It’s quite hard for a beginner like me, so I’m here to ask and I would really appreciate if you guys could help me out with this.


Answer
via

Use PHP’s multiline modifier for this, that way you’re able to detect leading numbers in each line independently and remove the undesirable characters from the beginning of each of those lines.

See: https://regex101.com/r/G3AzSx/1

<?php
$string = '
01. A little love (2002)
02 - No.1 Star
03 Love Story
';
$string = preg_replace('/^[0-9.s-]+/m', '', $string);

That gives you:

A little love (2002)
No.1 Star
Love Story

Breaking this down for you:
/^[0-9.s-]+/m

  • Beginning of a line in multiline mode ^
  • Followed by one or more numbers 0-9, a dot ., whitespace s, or dashes -.
Share This
Posted in: