[英]PHP Regex for this pattern
Need help with a regular expression. 需要有关正则表达式的帮助。
1) Format: 1)格式:
Advisor Geologist – HighMount Exploration & Production LLC – Oklahoma City, OK
I'd like to get the text between the last character and the dash. 我想在最后一个字符和破折号之间输入文本。 ie. 即。 Oklahoma City, OK
. Oklahoma City, OK
。 Note the text might contain multiple dashes. 请注意该文本可能包含多个破折号。
Tried this: 试过这个:
~-([.*$]+)~
Trying to get between the dash and the end of the string (.*$). 试图在破折号和字符串结尾之间(。* $)。 Need to know how to check for the last occurrence of the dash. 需要知道如何检查破折号的最后一次出现。
You don't need a regular expression, explode()
the string on the dash, and take the last element. 您不需要正则表达式,将破折号上的字符串explode()
并接受最后一个元素。
$str = 'Advisor Geologist – HighMount Exploration & Production LLC – Oklahoma City, OK';
$arr = explode( '–', $str);
$last = trim( end( $arr));
echo $last;
Much more efficient. 效率更高。
If you need a regex, this is the simplest one I can think of: 如果需要正则表达式,这是我能想到的最简单的一个:
'/\s*([^-]+)\s*$/'
Let's see how it works: 让我们看看它是如何工作的:
\\s*
matches zero or more whitespace characters (spaces, tabs, etc.) \\s*
匹配零个或多个空格字符(空格,制表符等) ([^-]+)
matches one or more characters that are not dashes ([^-]+)
匹配一个或多个非破折号的字符 \\s*
matches zero or more whitespace characters (spaces, tabs, etc.) \\s*
匹配零个或多个空格字符(空格,制表符等) $
matches the end of the string $
匹配字符串的结尾 Please note that what the –
character in your post is not a simple dash. 请注意,帖子中的–
字符不是简单的破折号。 It is some other Unicode character. 这是其他一些Unicode字符。 If you need to match that too, you should update the regex this way: 如果您也需要匹配它,则应通过以下方式更新正则表达式:
'/\s*([^-–]+)\s*$/'
Here is a code sample: 这是一个代码示例:
preg_match(
'/\s*([^-]+)\s*$/',
'Advisor Geologist – HighMount Exploration & Production LLC - Oklahoma City, OK',
$matches);
$city = $matches[1];
Also strrpos() can help. strrpos()也可以提供帮助。
$str = 'Advisor Geologist – HighMount Exploration & Production LLC – Oklahoma City, OK';
$result = trim(substr($str, strrpos($str, '-')+1));
For fixed formats you can use list() & explode()
: 对于固定格式,可以使用list() & explode()
:
$str = 'Advisor Geologist – HighMount Exploration & Production LLC – Oklahoma City, OK';
list($occupation, $company, $city) = explode('-', $str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.