获取连字符之前的字符串[重复]

问题描述 投票:0回答:4

所以我有一个分隔字符串,我需要获取分隔符之前的子字符串,让我们举个例子:

This string - DeleteMe please and some other text

所以我想找到

DDeleteMe please and some other text
并将其删除,因为我需要的只是
This string

php regex text-extraction
4个回答
2
投票

那么破折号

-
之前的所有内容或者
DeleteMe please and some other text
如何有资格被删除?

如果是这样,您不需要正则表达式,您可以使用

substr
strpos
:

$string = "This string - DeleteMe please and some other text";
$string = trim(substr($string, 0, strpos($string, '-')));

您也可以使用

explode()
:

$parts = explode('-', $string);
$string = trim($parts[0]);

2
投票

试试这个:

$fixed_string = preg_replace("(\s-.*)$", "", $your_string);

1
投票

你不需要正则表达式。

$str = 'This string - DeleteMe please and some other text';
$str = substr($str, 0, strpos($str, '-') - 1);

1
投票
$str = preg_replace('\s*-\s*DeleteMe.*$','', $str)
© www.soinside.com 2019 - 2024. All rights reserved.