正则表达式和 PHP:在 X 个字符后添加省略号
对于了解正则表达式的人来说应该相当简单。不幸的是,我不属于知情者。
在下面的示例中,如何将省略号附加到超过 27 个字符的任何内容,以便列出的第四个链接将显示为 http://iamanextremely.com/long/lin
?
<?php
$input = <<<EOF
http://www.example.com/
http://example.com
www.example.com
http://iamanextremely.com/long/link/so/I/will/be/trimmed/down/a/bit/so/i/dont/mess/up/text/wrapping.html
EOF;
$output = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,27})[^(\s|,)<]*)/",
'<a href="http://$2$3" rel="nofollow">http://$2$4</a>', $input);
Should be fairly simple for someone who knows regex. I am unfortunately not among those in the know.
How can one append ellipsis to anything over 27 chars in the below example, so that the fourth link listed will appear as http://iamanextremely.com/long/lin
?
<?php
$input = <<<EOF
http://www.example.com/
http://example.com
www.example.com
http://iamanextremely.com/long/link/so/I/will/be/trimmed/down/a/bit/so/i/dont/mess/up/text/wrapping.html
EOF;
$output = preg_replace("/(http:\/\/|(www\.))(([^\s<]{4,27})[^(\s|,)<]*)/",
'<a href="http://$2$3" rel="nofollow">http://$2$4</a>', $input);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
preg_replace_callback
对所有匹配的网址应用回调。在回调中,您可以随心所欲地制作精美的东西。(ps.我只是从你的正则表达式开始,我不认为匹配网址应该那么麻烦。)
You could use
preg_replace_callback
to apply a callback to all matched urls. In the callback you can make stuff as fancy as you wish.(ps. I just took your regexp to start with, I don't think matching a url should be that cumbersome.)
除非您需要匹配特定格式,即仅匹配 http:// 链接,否则正则表达式就太过分了。只需使用字符串函数并循环遍历您的网址来测试其长度。如果您想变得更奇特,请使用
explode()
和array_walk()
Unless you need to match a specific format, i.e. only the http:// links, a regex is overkill. Just use string functions and loop over your urls testing their length. If you want to get fancy, use
explode()
andarray_walk()
如果这是为了在 HTML 页面中显示,您可以考虑使用 CSS 来设置省略号的样式,而不是手动截断它。
您将使用类似这样的 CSS:
然后,即使 HTML 代码包含完整的字符串,文本也会在屏幕上被截断并给出省略号。
此技术并不适合所有情况,但在它有效的情况下,它是在将内容发送给用户之前对内容进行修改的绝佳替代方案。
重要提示:当前版本的 Firefox 浏览器不显示省略号。但它仍然可以正确截断,所以这不是一场灾难。所有其他浏览器都会显示这些点,希望很快发布的新版 Firefox 也会添加它。
If this is for display in an HTML page, you might consider using CSS to style it with an ellipsis rather than manually truncating it.
You would use CSS something like this:
The text would then be truncated on screen and be given an ellipsis, even though the HTML code contained the full string.
This technique is not suited to all cases, but where it works it is an excellent alternative to hacking around with your content before sending it to the user.
One important note: The current version of Firefox browser doesn't display the ellipsis dots. It does still truncate correctly though, so it's not a disaster. All other browsers do show the dots, and hopefully a new version of firefox due soon will add it too.