轻松替换 PHP
我希望字符串的第一个单词被标签包围。用我的代码插入所有单词都被它包围。
该代码适用于 WordPress,因此 the_title 是帖子的标题。例如。你好世界。 我希望它是 Hello World
。
<?php
$string = the_title('', '', false);
$pattern = '^(\S+?)(?:\s|$)^';
$replacement = '<span>$1</span>';
$string = preg_replace($pattern, $replacement, $string);
?>
<h2><a href="<?php the_permalink(); ?>"><?=$string?></a></h2>
抱歉我的英语不好:)
我的解决方案:
<?php
$string = the_title('', '', false);
$pattern = '/\S+/';
$replacement = '<span>$0</span>';
$string = preg_replace($pattern, $replacement, $string, 1);
?>
<h2><a href="<?php the_permalink(); ?>"><?=$string?></a></h2>
I want the first word of the string to be surrounded by tags. Insted with my code all the words gets surrounded by it.
The code is for a wordpress so the_title is the title of the post. Eg. Hello World.
I want it to be <span>Hello </span>World
.
<?php
$string = the_title('', '', false);
$pattern = '^(\S+?)(?:\s|$)^';
$replacement = '<span>$1</span>';
$string = preg_replace($pattern, $replacement, $string);
?>
<h2><a href="<?php the_permalink(); ?>"><?=$string?></a></h2>
Sorry for my bad english :)
MY SOLUTION:
<?php
$string = the_title('', '', false);
$pattern = '/\S+/';
$replacement = '<span>$0</span>';
$string = preg_replace($pattern, $replacement, $string, 1);
?>
<h2><a href="<?php the_permalink(); ?>"><?=$string?></a></h2>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试通过将
1
作为第四个参数传递给preg_replace
来将替换数量限制为1
:更好的查找单词的正则表达式将使用 word边界:
但这样你就必须再次将替换限制为
1
。或者,您可以将第一个单词匹配为:
并仅使用
preg_replace
而不限制替换数量。注意:
\w
=[a-zA-Z0-9_]
如果您的单词允许包含其他字符,请进行适当更改。如果您将任何非空白视为单词字符,则可以使用\S
。Try limiting the number of replacements to
1
by passing1
as the 4th argument topreg_replace
as:A better regex to find words would be using word boundaries:
but this way you'll have to restrict the replacement to
1
again.Alternatively you can just match the first word as:
and just use
preg_replace
without limiting number of replacements.NOTE:
\w
=[a-zA-Z0-9_]
if your word is allowed to have other characters, change suitably. If you consider any non-whitespace as a word character you can use\S
.使用类似以下内容:
Use something like the following:
您必须像这样更新模式和替换(这会忽略开头的第一个空格):
You have to update the pattern and the replacement like this (this ignores first whitespaces at the beginning):
在这种情况下不需要 PCRE。您可以使用简单的
substr
/strpos
组合来执行相同的操作(尽管速度至少应该更快):如果您确实想采用 PCRE 方式,您可以do:
该语句不需要
$limit
,因为该模式以^
(字符串开头)开头,它不是分隔符,与您的不同。PCRE is not necessary in this case. You could do the same with a simple
substr
/strpos
combination (which should, although minimally, be faster):If you really want to go with the PCRE way, you can do:
The statement does not require a
$limit
, because the pattern starts with a^
(beginning of string), which is not a delimiter, unlike yours.$string = '"' . substr($string, 0, strpos($string, ' ')) . '"';
应该可以解决问题!$string = '"' . substr($string, 0, strpos($string, ' ')) . '"';
ought to do the trick!