0

I have a huge code that has numbers between some lines: eg:

code code code
7362
code code code
code code code
code code code
63
code code code
...

I want to remove this numbers, between code to become:

code code code
code code code
code code code
code code code
code code code

I tried:

$a = preg_replace("/(s[0-9,]+s)/", "", $a);

but it is not working.

/(s[0-9,]+s
RGS
  • 4,062
  • 4
  • 31
  • 67

4 Answers4

1

You forget to escape 's'

$a = preg_replace("/(\s[0-9,]+\s)/", "", $a);

And coma after 9 is not necessary.

Michał M
  • 618
  • 5
  • 13
  • However, this `\s[0-9,]+\s` will remove line breaks and won't find numbers at the start/end of the string. Actually, this will remove numbers anywhere, not just number-only strings. – Wiktor Stribiżew Aug 24 '16 at 07:38
1

The best way to remove digit-only lines is to use

'~^\d+$\R*~m'

See the regex demo

Pattern details:

  • ^ - start of line (since ~m MULTILINE modifier enables ^ to match the start of a line, not string)
  • \d+ - 1 or more digits
  • $ - end of line
  • \R* - zero or more line breaks (any sequence like LF, CR, CR+LF).

PHP demo:

$str = "code code code\n7362\ncode code code\ncode code code\ncode code code\n63\ncode code code\n..."; 
$result = preg_replace('~^\d+$\R*~m', '', $str);
echo $result;
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
-1

This will remove all digits:

$words = preg_replace('/[0-9]+/', '', $words);
jmattheis
  • 10,494
  • 11
  • 46
  • 58
Kamlesh Gupta
  • 505
  • 3
  • 17
-1

I tried this its working for me.

/[1-9][0-9]*/g
Ahmed Jehanzaib
  • 158
  • 1
  • 10