1

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.

3 Answers 3

1

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.
Sign up to request clarification or add additional context in comments.

Comments

1

Try to use preg_replace instead

2 Comments

can you give me an example of how i would do that? I did play around with a bit but i wasn't able to get it going.
If I got it correctly, you have all data as a plain text in $teststring. Then extract the samples with your original pattern into $data , so you get your $data array populated. After this apply to $data the following: $data = preg_replace('/\\s+/','\\$',$data);
1

Use:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.