-1

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.

4 Answers4

0

I strongly suggest that you go to Online regex tester and debugger. You will learn a lot about regular expressions and will begin to think that things are usually not so hard as they appear to be.

In your case, let's suppose that each line is in $line. Please go to this question if your data is in a file. Let's also suppose that your desired output is

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

You coud do that in various ways. One of them

$pattern = '/(^\d+\W+)(\w+.*)/';
$result = preg_replace($pattern, '$2', $line);
J.M. Robles
  • 614
  • 5
  • 9
0

You could try something simple as \d{2}[.\-\s]+.

An example would be:

echo preg_replace('@\d{2}[.\-\s]+@', '', $str);

Output

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

Demo: https://regex101.com/r/hN6jFd/1/

Ibrahim
  • 6,006
  • 3
  • 39
  • 50
0

For fastest results (see the step count at regex101), use:

/^[^A-Z]+/m Pattern Demo Link

  • a starting anchor ^.
  • a negated character class listing all capital letters
  • a greedy "one or more" quantifier
  • and a multi-line flag/modifier at the end of the pattern

Output:

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

PHP Code: (Demo)

$input='01. A little love (2002)
02 - No.1 Star
03 Love Story';

echo preg_replace('/^[^A-Z]+/m','',$input);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
0

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 \-.
jaswrks
  • 1,255
  • 10
  • 13