从字符串中删除最后两个单词 [英] Remove last two words from a string

查看:37
本文介绍了从字符串中删除最后两个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 preg_replace 完全陌生,但下面的代码从我的字符串中删除了最后一个单词:

I am totally new to preg_replace, but the code below removes the last word from my string:

preg_replace('/\W\w+\s*(\W*)$/', '$1', $var);

我正在尝试修改它,以便删除最后的两个字.

I am trying to modify it, so that it removes the last two words.

我唯一能想到的就是将 $1 替换为 $2,但这似乎根本没有任何效果,而且可能只是愚蠢的:/

The only thing that I could think of was to replace $1 with $2, but this seems to not have any effect at all and was probably just dumb :/

有问题的字符串看起来有点像这样:

The string in question looks kinda like this:

Lorem ipsum dolor sit amet. Source: LOREM

我想删除来源:LOREM

推荐答案

一个简单的正则表达式可以匹配一个空格,后跟任意数量的字母(或冒号),后跟一个空格,后跟任意数量的字母字符串的结尾:

A simple regular expression could match a space, followed by any number of letters (or a colon), followed by a space, followed by any number of letters at the end of a string:

$str = "Lorem ipsum dolor sit amet. Source: LOREM";
$str = preg_replace( "/\s[a-z:]+\s[a-z]+$/i", "", $str );

// Lorem ipsum dolor sit amet.
echo $str;

分解的表达式如下:

\s       // Single space
[a-z:]+  // Any letter, a to z, or a colon, 1 or more times
\s       // Single space
[a-z]+   // Any letter, a to z, 1 or more times
$        // End of string

演示:http://codepad.org/G22LnDDY

另一种方法是使用 explode 创建一个单词数组,并删除最后两个.

One other method would be to use explode to create an array of words, and remove the last two.

$str = "Lorem ipsum dolor sit amet. Source: LOREM";
$words = explode( " ", $str );
array_splice( $words, -2 );

// Lorem ipsum dolor sit amet.
echo implode( " ", $words );

演示:http://codepad.org/6XwqvwuP

这篇关于从字符串中删除最后两个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆