I’m using php’s preg_replace().
Basically I have 2 possibilities of a string to match:
- Hello Real World
- Greetings
Here’s what I wish to accomplish:
Hello </span>Real WorldGree</span>tings
Rule explained: if a string contains space(s), insert </span> right after the first space character. If a string contains no space(a word), insert </span> right at the middle(+/- if odd character count) of the string.
So far, I have came up with a long working solution:
<?php
$str = "Hello Real World";
echo preg_match("/ /", $str) ? preg_replace("/ /", " </span>", $str, 1) : preg_replace("/.{" . round(strlen($str)/2) . "}/", "$0</span>", $str, 1);
?>
However, I believe it can be accomplished with a much shorter and elegant regex with only a single preg_replace() call.
Any idea how to do it with only single preg_replace() call? e.g.:
preg_replace("/ |.{" . round(strlen($str)/2) . "}/", "$0</span>", $str, 1)
The regular expression engine doesn’t know ahead of time if there is a space in the string. You don’t need regular expressions to do this at all, although you do need multiple functions: