dot
dot

Reputation: 15660

regular expression to find spaces is failing

I'm trying to use a regular expression to find groups of spaces and replace them with another character like $

 $teststring="00005e-000003 D21    3       0004ea-287342 D21    3       000883-d94982 D21    3       000f20-4c5241 D21    3       002561-e32140 D21    3       003018-a1a24f D21    3       00e039-0fe0fe D21    3       08000f-1eb958 D21    3       08000f-1ec4de D21    3       082e5f-498900 D21    3";
 $pattern='/([0-9A-F]{6})-([0-9A-F]{6}) ([0-9A-F]+)\s{1,}([0-9]{1,})/i'; 

 if (preg_match_all($pattern,$teststring,$matches, PREG_PATTERN_ORDER)) {   
        $data = $matches[0];
 }

this is working in that based on my pattern, if i do a print_r on $data, it looks like:

 Array ( 
          [0] => 00005e-000003 D21 3 
          [1] => 0004ea-287342 D21 3 
          [2] => 000883-d94982 D21 3 

       }

what I'd like to do is replace all spaces with $ so the output looks like this:

 Array ( 
          [0] => 00005e-000003$D21$3 
          [1] => 0004ea-287342$D21$3 
          [2] => 000883-d94982$D21$3 
  }

Can you tell me how i can accomplish this?

Thanks.

Upvotes: 1

Views: 81

Answers (3)

xbakesx
xbakesx

Reputation: 13500

If all you want to do is replace all groups of spaces with one dollar sign, you can do something like this:

preg_replace('/\s+/','$', $subject);

Also as an aside:

  • You can use \d instead of [0-9] to match one digit
  • You can use + to match one or more character instead of {1,}
  • Instead of using //i to do a case-insensitive search, I think making your hex character class [0-9a-fA-F] would be a little more efficient... though I didn't do the leg work.

Upvotes: 1

xdazz
xdazz

Reputation: 160843

Use:

$ret = preg_replace('/([\da-f]{6}-[\da-f]{6}) ([\da-f]+)\s+(\d+)/i', '\1$\2$\3', $teststring);

Upvotes: 1

Serge
Serge

Reputation: 6095

Try to use preg_replace instead

Upvotes: 1

Related Questions