Skip to content

Instantly share code, notes, and snippets.

@christeredvartsen
Last active December 14, 2015 02:18
Show Gist options
  • Save christeredvartsen/5012295 to your computer and use it in GitHub Desktop.
Save christeredvartsen/5012295 to your computer and use it in GitHub Desktop.
Replace _words_ in a string with <em>words</em> but not when they are inside an URL
<?php
// Lookbehinds require fixed length, but lookaheads does not, so just reverse the string
$string = 'some string with _foo_ and _bar_ and http://example.com/some_foo_bar';
$replaced = strrev(preg_replace('#_([a-zæøå -]+)_(?![^ ]+//:ptth)#i', '>me/<\1>me<', strrev($string)));
echo $replaced; // some string with <em>foo</em> and <em>bar</em> and http://example.com/some_foo_bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment