I am using a self generated navigation using php. I need to wrap the first and second word in separate div classes. e.g.
<li> <span>First</span> <span class="word">Second</span> Word </li>
At the moment i can wrap the first word in a span class using
$name = preg_replace('/(?<=\>)\b(\w*)\b|^\w*\b/', '<span>$0</span>', $ni->name);
Does anyone know how I can alter this to wrap the first two words?
You could split the words up in an array and replace the indexes you need.
// Split on spaces.
$name = preg_split("/\s+/", $name);
// Replace the first word.
$name[0] = "<span>" . $name[0] . "</span>";
// Replace the second word.
$name[1] = "<span>" . $name[1] . "</span>";
// Re-create the string.
$name = join(" ", $name);
I don't know if I understood you well, but I think you need this:
$string = '<li> <span>First</span> <span class="word">Second</span> Word </li>';
$name = preg_replace('/(<span(?:.*)>(\w*)<\/span>)/U', '<div>$2</div>', $string);
echo htmlspecialchars($name);
// <li> <div>First</div> <div>Second</div> Word </li>
or
$string = '<li> First Second Word </li>';
$name = preg_replace('/<[\/]?\w*>(*SKIP)(*FAIL)|\b(\w+)\b(\s*)(\w+)\b/U', '<span>$1</span>$2<span class="word">$3</span>', $string);
echo htmlspecialchars($name);
// <li> <span>First</span> <span class="word">Second</span> Word </li>