Regular expression for number


I have some strings as follows:


So long so good.

What I need, is via PHP and regular expression, replace any character before that first hiffen (-), for some text, only the first. Staying for example


Can anyone help me?

asked by anonymous 06.05.2016 / 00:04

2 answers


Use the preg_replace() function to make the substitution with a /\d+-/ regex, the important part is to enter the fourth argument that is the number of substitutes that will be made.

\d+- means to find in the string one or more digits followed by a dash anywhere in the string.

   $str = '99-01[10-10-2010] ALL-06[11-12-2016]';
   $str = preg_replace('/\d+-/', 'ALL-', $str, 1);
  echo $str;

Example - ideone

If string has multiple rows you can solve it differently, taking only the specified pattern at the beginning of each line with the s .


$str = "99-01[10-10-2010]

$str = preg_replace('/^\d+-/s', 'ALL-', $str);

echo $str;

Example 2

06.05.2016 / 00:13

I know you asked for a RegEx , and @rray posted the solution that does exactly what you requested (and that has already taken my +1). Anyway I find it important to comment that PHP already has a solution made as a glove for your specific case, and does not need RegEx .

Just this, clean and short of writing:

'ALL'.strstr( '99-01[10-10-2010]', '-' );

An example code:

$s = '99-01[10-10-2010]';
echo 'ALL'.strstr( $s, '-' );

Iterating an array :

$strings = array(

foreach( $strings as $s ) echo 'ALL'.strstr( $s, '-' );

See working at IDEONE .

06.05.2016 / 00:52