Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to retrieve a substring in PHP that starts and ends with something, and then replace it in PHP?

Let’s say I have a string like this:

This is just a test {#3,2,7,9} this is another test {#21,2,11}

How can I retrieve all instances of {#x,y,..} and replace it with a random number it contains?

For example, the string above could become:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is just a test 2 this is another test 11

>Solution :

Regex match the string inside preg_replace_callback, split the match into array, shuffle it and return.

<?php
$str = 'This is just a test {#3,2,7,9} this is another test {#21,2,11}';

echo preg_replace_callback('/{[#]([\w,]{1,})}/', function ($match)  {
  $numbers = explode(',', $match[1]);
  shuffle($numbers);
  return isset($numbers[0]) ? $numbers[0] : '{#'.$match[0].'}';
}, $str);

See online, https://3v4l.org/luCAT

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading