如何在PHP中用正则表达式删除前导字符和查询字符


How to remove leading characters and the query character with a regular expression in PHP?

我使用preg_replace()和正则表达式来删除连字符(-)之前的所有字符。我想更新表达式,同时删除连字符本身。完整的代码行显示在下面的上下文中。

$item['options']['Size'] = preg_replace('/^[^-]*/', '', $item['options']['Size']);

因此,假设我有以下字符串:

测试123-150X200

当前的preg_replace函数将留给我:

-150X200

我想以结束

150X200

有人能建议我如何更新regular_expression来实现这一点吗。感谢

您可以在模式末尾添加连字符。

$item['options']['Size'] = preg_replace('/^[^-]*-/', '', $item['options']['Size']);
                                                ^

通过这种方式,连字符匹配(=消耗)并将被删除。注意,[^-]是与除-之外的任何字符匹配的否定字符类。因此,连字符与原始正则表达式不匹配。

非正则表达式方法:

$item['options']['Size'] = ltrim(strstr($item['options']['Size'], '-'),'-');

请参阅IDEONE演示

<?php
$item = 'TEST123-150X200'; // string here
echo preg_replace('/^[^-]*-/', '', $item);
?>

除了给出的答案/注释外,您还可以使用正面的lookbacking并替换它:

<?php
$str = "TEST123-150X200";
$regex = '/.*(?<=-)/i';
$item['options']['Size'] = preg_replace($regex, '', $str);
// output: 150X200
?>

或者(如注释中所述),从1:开始计数

$item['options']['Size'] = substr(preg_replace('/^[^-]*/', '', $item['options']['Size']), 1);

我认为它不需要正则表达式。。。

$str = "TEST123-150X200";
var_dump(end(explode("-", $str))); //string(7) "150X200"
var_dump(ltrim(strstr($str, "-"), "-"));//string(7) "150X200"
var_dump(substr(strrchr($str, "-"), 1) );//string(7) "150X200"