How do I optionally match the start ^
or end $
of a line in a regular expression?
For example:
/(?<=[\s\^])/
does not match starts with space character or start of line.
My problem was in PHP matching the following.
$str = '**bold** **bold** **bold**';
echo preg_replace('/(?<=\s|^)\*\*(.+?)\*\*(?=\s|$)/', '<strong>\\1</strong>', $str);
My edge cases that were the bold at the start and end of the string were not being matched. Some edge cases I came across with other variants were matching within strings, matching chains of asterisks, and countless other problems.
echo preg_replace('/(?<=^|\s|\>)[\*]{2,}(?=[^\s\*])(.+?)(?<=[^\s\*])[\*]{2,}(?=\s|\<|$)/', '<strong>\\1</strong>', $str);