Hermes
Hermes

Reputation: 462

Php get specific word in string

I have a url. I want to parse url. I don't want to get last two value. How can I do?

$str="first-second-11.1268955-15.542383564";

As I wanted

$str="first-second";

I used this code. But I don't want to get - from last value

$arr = explode("-", $str);
for ($a = 0; $a < count($arr) - 2; $a++) {                
    $reqPage .= $arr[$a] . "-";       
}

Upvotes: 0

Views: 2585

Answers (3)

Thushan
Thushan

Reputation: 1350

Regex is the fastest way for the string manipulations. Try this.

$str="first-second-11.1268955-15.542383564";
preg_match('/^[a-z]*-{1}[a-z]*/i', $str, $matches);
$match = count($matches) > 0 ? $matches[0] : '';

echo $match;

Upvotes: 0

Maryam
Maryam

Reputation: 375

You can use regular expressions too.Those are patterns used to match character combinations in strings.:

W*((?i)first-second(?-i))\W*

Upvotes: 2

B001ᛦ
B001ᛦ

Reputation: 2059

Use the 3rd param of explode() called limit:

$str="first-second-11.1268955-15.542383564";
$arr = explode("-", $str, -2);
$reqPage = implode($arr, "-"); // contains "first-second"

Upvotes: 1

Related Questions