0

I have a function which is containing multiple REGEX. Here is my function:

function generate($str) {
  $str = preg_replace(/\*\*(.*?)\*\*/, "<b>$1</b>", $str);
  $str = preg_replace(/__(.*?)__/, "<u>$1</u>", $str);
  $str = preg_replace(/\*(.*?)\*/, "<i>$1</i>", $str);
  $str = preg_replace(/--(.*?)--/, "<del>$1</del>", $str);
  $str = preg_replace(/`(.*?)`/, "<code>$1</code>", $str);
  return $str;
}

Now I want to know is this ^ the standard way? Overwriting several times on one variable? Is there any better approach?

3
  • 4
    RTM: php.net/manual/en/function.preg-replace.php You can do everything in one call Commented Dec 22, 2015 at 14:23
  • @Rizier123 Do you mean something like what the followed answer said? Commented Dec 22, 2015 at 14:36
  • Yes, read the manual there is everything documented. Commented Dec 22, 2015 at 14:38

1 Answer 1

2

The documentation for preg_replace says that the first two parameters can be arrays or strings. If they are arrays, each match in the first array will be replaced by the corresponding string in the second array. E.g.:

function generate($str) {
  return preg_replace(
    array(
      '/\*\*(.*?)\*\*/',
      '/__(.*?)__/',
      '/\*(.*?)\*/',
      '/--(.*?)--/',
      '/`(.*?)`/'
    ),
    array(
      "<b>$1</b>",
      "<u>$1</u>",
      "<i>$1</i>",
      "<del>$1</del>",
      "<code>$1</code>"
    ),
    $str
  );
}
Sign up to request clarification or add additional context in comments.

2 Comments

Good solution. return preg_replace(...) should be enough here.
Yes, that's a good simplification. I edited the answer to reflect this.

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.