How to split or explode string with first non alphanumeric char - PHP

时间:2017-08-04 12:49:52

标签: php split

Strings:
iPhone 7 plus - space grey (New)
iPhone6 plus, brand new, (Used)
iPhone 5 ( black)

Required as:
iPhone 7 plus
iPhone6 plus
iPhone 5

How do i split above strings with first Non Alphanumeric Char using a regular expression?

4 个答案:

答案 0 :(得分:2)

If you don't need the second part, just match the first:

preg_match('/[A-Z0-9\s]+/i', $string, $match);
echo $match[0];

Match letters A-Z, numbers 0-9 and spaces \s one or more times + case-insensitive i.

答案 1 :(得分:1)

A simple preg_match should do the trick.

preg_match("/[a-zA-Z0-9 ]+/", $str, $match);

It will match words (a-Z), numbers and spaces, more than one.

http://www.phpliveregex.com/p/kW8

答案 2 :(得分:0)

You can use regular expression to do it.

$input = 'iPhone6 plus, brand new, (Used)';
$items = preg_split('/[^A-Za-z0-9\s]/i', $input);
echo $items[0];

答案 3 :(得分:0)

更准确地说,您的任务应描述为“如何从列出的字符的第一次出现开始修剪尾随的字符?”。以此方式重新声明后,很明显,在返回前导子字符串之前,将输入字符串拆分/分解为数组是不必要的步骤。

大多数情况下,您想用空字符串替换字符串中不需要的部分。

对于最干净的输出字符串,还需要考虑其他一些事项,以便在首次出现列出的字符之前删除可选空格。这样可以避免替换后额外的rtrim()调用。

代码:(Demo

$strings = [
    'iPhone 7 plus - space grey (New)',
    'iPhone6 plus, brand new, (Used)',
    'iPhone 5 ( black)',
];

var_export(preg_replace('~ ?[-,(].*~', '', $strings));

输出:

array (
  0 => 'iPhone 7 plus',
  1 => 'iPhone6 plus',
  2 => 'iPhone 5',
)

(为记录起见,preg_replace()在输入字符串而不是演示中的数组时工作原理相同)

模式:

 ?     # match zero or one literal space (there is a space before the question mark)
[-,(]  # match one of the listed characters
.*     # match zero or more characters to the end of the string/line