php - 将前三个单词包裹在一个跨度中
问题描述
我想过滤 the_content 以将第一段的前三个单词包装在 span 标记中。到目前为止,这是我的代码:
function first_paragraph($content) {
if(is_single()) {
return preg_replace('regex goes here', "<p><span>$1</span>", $content, 1);
}
}
add_filter('the_content', 'first_paragraph');
到目前为止,我没有找到任何匹配第一段前三个单词的正则表达式和替换。
有什么帮助吗?
谢谢!
解决方案
像这样:
php > $content = 'The quick brown fox jumped over the lazy dog.';
php > echo preg_replace('/^((\S+\s+){2}\S+)/', '<span>$1</span>', $content);
<span>The quick brown</span> fox jumped over the lazy dog.
所以,你会想要这个:
function first_paragraph($content) {
if(is_single()) {
return preg_replace('/^((\S+\s+){2}\S+)/', "<p><span>$1</span>", $content, 1);
}
}
add_filter('the_content', 'first_paragraph');
请记住,如果$content
少于四个单词,则正则表达式将不匹配并且不会发生替换。
推荐阅读
- ios - 有时无法加载激励视频广告
- c++ - QGeoCodingManager 没有给出错误但没有结果
- python-3.x - Selenium webdriver.Remote 在 Linux 上出现 SSL 错误,适用于 macOS
- javascript - 当我点击它时,视频无法在手机上播放
- uml - 通信图或系统序列图中的接口描述?
- linux - 找不到 libisl.so.15
- scala - 如何运行 akka-sample-distributed-data-scala 演示
- php - Sabre Webservices EnhancedAirBook 带婴儿
- php - 我在一个树枝页面中同时渲染了登录和注册控制器,但它一直给我错误
- amazon-web-services - 使用推荐的配置后,当存储桶不兼容时,AWS CLI S3 同步仍然失败