-2

I want to obtain a part of a string up until the first non-alphanumeric character. Currently, I have the following strings with what I would like to show.

Go Forty Go (IRE) 471    -> Go Forty Go
Pearl Noir 15528258 D3   -> Pearl Noir
Synonym (ITY) 1793158-00 D1   -> Synonym

In the above cases, I want to pull characters before either a number or a (.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
emma perkins
  • 749
  • 1
  • 10
  • 28

3 Answers3

1

Do you mean this:

$repl = preg_replace('/\h*[^ a-zA-Z].*$/', '', $input);
Go Forty Go
Pearl Noir
Synonym

btw this is removing after first non-alphabetic+non-space character.

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

You can use the following regex:

/^.*?(?=\s*[^\s\p{L}])/

$str = "Go Forty Go (IRE) 471    -> Go Forty Go";
$str2 = "Pearl Noir 15528258 D3   -> Pearl Noir";
$str3 = "Synonym (ITY) 1793158-00 D1   -> Synonym";
preg_match('/^.*?(?=\s*[^\s\p{L}])/', $str, $match);
echo $match[0] . PHP_EOL;
preg_match('/^.*?(?=\s*[^\s\p{L}])/', $str2, $match1);
echo $match1[0] . PHP_EOL;
preg_match('/^.*?(?=\s*[^\s\p{L}])/', $str3, $match2);
echo $match2[0] . PHP_EOL;

See IDEONE code

Output:

Go Forty Go
Pearl Noir
Synonym

The "core" of the regex is (?=\s*[^\s\p{L}]) look-ahead that makes matching stop at a non-letter or space preceded with optional whitespace (to trim the output).

If you have Unicode letters in your input, add u flag:

/^.*?(?=\s*[^\s\p{L}])/u
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

Try this -

>>> preg_match_all("/^(.*?)\s*[(0-9]/m",$s, $matches)
=> 3
>>> $matches[1]
=> [   
       "Go Forty Go",
       "Pearl Noir",
       "Synonym"
   ]
Kamehameha
  • 5,423
  • 1
  • 23
  • 28