Wrap first and second word in span Clases PHP

二次信任 提交于 2019-12-22 12:42:57

问题


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?


回答1:


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);



回答2:


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>


来源:https://stackoverflow.com/questions/25303746/wrap-first-and-second-word-in-span-clases-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!