Dave Kiss
Dave Kiss

Reputation: 10495

PHP - Get all characters before an array of characters

I have two strings:

email-info and info/email

I need to retrieve all of the characters before - or / appears, so that, after being formatted, the strings look like this:

email and info

What is the best way to do this?

Upvotes: 0

Views: 465

Answers (4)

rabudde
rabudde

Reputation: 7722

$name = preg_replace('/[-\/](.*)$/', '', $email);

Upvotes: 0

squinlan
squinlan

Reputation: 1805

Jason's right. Here's a way to do it with string functions:

$str1 = "email-info";
$result = substr($str1, 0, strlen($str1) - strpos('-'));

Upvotes: 1

marklar
marklar

Reputation: 502

You can use PHP's split method

$StringYouWant = split($StringNeedsSplitting, '(-|/)')[0]

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 73011

This is pretty trivial for regular expressions. That is to say you could use something else (i.e. string functions).

Nonetheless, here's an example using preg_split():

$parts = preg_split('/[-\/]/', $string);

Upvotes: 2

Related Questions