用正则表达式去掉标点符号?
我做了这个函数来限制输出中字符串的长度,
/* limit the lenght of the string */
function limit_length($content, $limit)
{
# strip all the html tags in the content
$output = strip_tags($content);
# count the length of the content
$length = strlen($output);
# check if the length of the content is more than the limit
if ($length > $limit)
{
# limit the length of the content in the output
$output = substr($output,0,$limit);
$last_space = strrpos($output, ' ');
# add dots at the end of the output
$output = substr($output, 0, $last_space).'...';
}
# return the result
return $output;
}
它工作正常,但我认为它并不完美......例如,我在字符串中有这个文本,
Gender Equality; Radicalisation; Good Governance, Democracy and Human Rights;
这就是我使用该函数的方式,
echo limit_length($item['pg_description'], 20);
然后它返回,
Gender Equality;...
当您想告诉人们内容/行中有更多文本时,使用 ;...
看起来不太好。
我在想是否可以使用正则表达式来检查 ...
之前是否存在标点符号,然后将其删除。
是否可以?我怎样才能编写表达式来改进我的功能,以便可以“防弹”?
谢谢。
I made this function to limit the length of a string in the output,
/* limit the lenght of the string */
function limit_length($content, $limit)
{
# strip all the html tags in the content
$output = strip_tags($content);
# count the length of the content
$length = strlen($output);
# check if the length of the content is more than the limit
if ($length > $limit)
{
# limit the length of the content in the output
$output = substr($output,0,$limit);
$last_space = strrpos($output, ' ');
# add dots at the end of the output
$output = substr($output, 0, $last_space).'...';
}
# return the result
return $output;
}
it works fine but I think it is not perfect... for instance, I have this text in the string,
Gender Equality; Radicalisation; Good Governance, Democracy and Human Rights;
and this is how I use the function,
echo limit_length($item['pg_description'], 20);
then it returns,
Gender Equality;...
As you can it doesn't look great with ;...
when you want to tell people that there are more text inside the content/ line.
I was thinking if there is possible to use regular expression to check if there is any punctuation mark present before ...
then remove it.
Is it possible? How can I write the expression to improve my function so that can be sort of 'bulletproof'?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要删除除三个句点之前的字母以外的任何内容(根据需要进行调整):
$foo = preg_replace("[a-zA-Z0-9]+\.{3}", "...", $foo );
To remove anything other than letters directly preceding three periods (adjust as necessary):
$foo = preg_replace("[a-zA-Z0-9]+\.{3}", "...", $foo);