Regular expression for number

Asked

Viewed 90 times

6

I have some strings as follows:

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

So far so good.

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

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

Someone can help me?

2 answers

6

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

\d+- means to find in the string one or more digits followed by a dash on any part of 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 lines it can solve otherwise, taking only the specified pattern at the beginning of each line with the modifier 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

4

I know you asked for one Regex, and @rray posted the solution that does exactly what you asked (and already took my +1). Anyway I think it’s important to comment that PHP already has a solution made as a glove for your specific case, and that does not need to Regex.

Just that, clean and short to write:

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

An example code:

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

Iterating on a 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 on IDEONE.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.