[英]PHP: Regular Expression to delete text from a string if condition is true
I have a variable containing a string. 我有一个包含字符串的变量。 The string can come in several ways:
字符串可以通过几种方式出现:
// some examples of possible string
$var = 'Tom Greenleaf (as John Dunn Hill)'
// or
$var = '(screenplay) (as The Wibberleys) &'
// or
$var = '(novella "Four Past Midnight: Secret Window, Secret Garden")'
I need to clean up the string to get only the first element. 我需要清理字符串以仅获取第一个元素。 like this:
像这样:
$var = 'Tom Greenleaf'
$var = 'screenplay'
$var = 'novella'
I know this is a bit complicated to do but there is a pattern we can use. 我知道这有点复杂,但是我们可以使用一种模式。
Looking at the first variable, we can first check if the string contains the text ' (as'. If it does then we need to delete ' (as' and everything that comes after that. 查看第一个变量,我们首先可以检查字符串是否包含文本'(as.。如果是,那么我们需要删除'(as'以及之后的所有内容。
In the second variable the rule we made in the first one also applies. 在第二个变量中,我们在第一个变量中制定的规则也适用。 We just need also to delete the parenthesis .
我们只需要删除括号即可。
In the third variable if ' (as' was not found we need to get the first word only and then delete the parenthesis. 在第三个变量中,如果未找到'(as),我们只需要获取第一个单词,然后删除括号即可。
Well, thas all. 好吧,这一切。 I just need someone to help me do it because I'm new to PHP and I don't know regular expressions.... or another way to do it.
我只需要一个人来帮助我完成此任务,因为我是PHP的新手,并且我不知道正则表达式...。
Thanks!!!! 谢谢!!!!
actually, there's no need for complex regex 实际上,不需要复杂的正则表达式
$var = 'Tom Greenleaf (as John Dunn Hill)';
$var = '(novella "Four Past Midnight: Secret Window, Secret Garden")';
$var = '(screenplay) (as The Wibberleys) &';
if ( strpos($var,"(as") !== FALSE ){
# get position of where (as is
$ind = strpos($var,"(as");
$result = substr($var,0,$ind);
}else {
# if no (as, split on spaces and get first element
$s = preg_split("/\s+/",$var);
$result = $s[0];
}
print preg_replace( "/\(|\)/","",$result);
Try this regular expression: 试试这个正则表达式:
(?:^[^(]+|(?<=^\()[^\s)]+)
This will get you either anything up to the first parenthesis or the first word inside the first parenthesis. 这将使您达到第一个括号之前的任何内容或第一个括号内的第一个单词。 Together with
preg_match
: 连同
preg_match
:
preg_match('/(?:^[^(]+|(?<=^\\()[^\\s)]+)/', $var, $match);
试试这个
^\\((?<MATCH>[^ )]+)|^(?<MATCH>[^ ]+)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.