Regular expression for number

6

I have some strings as follows:

99-01[10-10-2010]
59-06[11-12-2016]

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

ALL-01[10-10-2010]
ALL-06[11-12-2016]

Can anyone help me?

    
asked by anonymous 06.05.2016 / 00:04

2 answers

6

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.

<?php
   $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 .

<?php

$str = "99-01[10-10-2010]
59-06[11-12-2016]
99[333]
3333-ABC[99]88-XX";

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

echo $str;

Example 2

    
06.05.2016 / 00:13
4

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(
    '99-01[10-10-2010]',
    '29-02[10-11-2011]',
    '95-03[10-12-2013]',
    '88-04[10-10-2015]',
    '59-06[11-12-2016]'
);

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

See working at IDEONE .

    
06.05.2016 / 00:52