letsgettechnical
letsgettechnical

Reputation: 83

Delete Everything After a Special Character

I am new to regex, and I think this is my best solution. I am trying to find away to remove all text after a special character is found.

At the moment I am playing with

preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $word);

But as you probably know, that only removes all special charters, not everything after the first special character is found.

Upvotes: 0

Views: 715

Answers (4)

Kiril Tonev
Kiril Tonev

Reputation: 68

You could find the index of the first occurrence of the special character with preg_match() and then use substr().

Upvotes: 0

sch
sch

Reputation: 27506

If you want to remove every character starting from the first character different from a-zA-Z0-9_ %[].()%&-, you can use the following:

preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-].*/s', '', $word);

If instead, you want to remove every thing after a character from a-zA-Z0-9_ %[].()%&- is found, you can use the following:

preg_replace('/[a-zA-Z0-9_ %\[\]\.\(\)%&-].*/s', '', $word);

Upvotes: 1

honyovk
honyovk

Reputation: 2747

You can simply do

$word = "Overflow's";

preg_match('/[a-zA-Z0-9_]+/', $word, $matches);

print_r($matches);

Which returns:

Array
(
    [0] => Overflow
)

Upvotes: 0

jeroen
jeroen

Reputation: 91744

You can turn it around and use preg_match:

preg_match('/^[a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', $word, $matches);

$matches[0] will contain the value you are looking for.

Upvotes: 1

Related Questions