-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
  • 484,719
  • 26
  • 302
  • 397
emma perkins
  • 689
  • 1
  • 8
  • 25

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
  • 664,788
  • 59
  • 469
  • 547
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
  • 484,719
  • 26
  • 302
  • 397
0

Try this -

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