简体   繁体   English

PHP正则表达式:查找字符串中给定模式的首次出现

[英]PHP regex: find the first occurrence of a given pattern in a string

my string can be 我的绳子可以是

new-york-10036

or 要么

chicago-55036

the desired result is 理想的结果是

new-york
chicago

and i basically want to remove all the string that come after the first dash - followed by a number 我基本上想删除第一个破折号之后的所有字符串-后跟一个数字

seems easy but i don't know how 似乎很简单,但我不知道如何

You can use Negative Lookahead, like so: 您可以使用负前瞻,如下所示:

(.+)(?=\-\d)

The regex reads: "get me everything that is not followed by exactly one dash and exactly one number after that". 正则表达式显示为:“让我得到的所有不带一个破折号和一个跟在其后的数字”。

Given the input new-york-10036 the regex is going to capture only new-york . 给定输入new-york-10036 ,正则表达式将仅捕获new-york In PHP you can get the matched string with: 在PHP中,您可以通过以下方式获取匹配的字符串:

$string = 'new-york-10036';

$regex = '/(.+)(?=\-\d)/';

preg_match($regex, $string, $return);

echo $return[0] . "\n";

It outputs new-york . 它输出new-york

See the regex working here . 看到正则表达式在这里工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM