0

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] . "-";       
}
2
  • You can use array_pop() to remove last element from array and then you can implode the array using - Commented Jul 17, 2018 at 8:18
  • 1
    substr($reqPage, 0, -1) will remove last character of your string. Commented Jul 17, 2018 at 8:21

3 Answers 3

2

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

W*((?i)first-second(?-i))\W*
Sign up to request clarification or add additional context in comments.

Comments

1

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"

Comments

0

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;

1 Comment

not fastest. from php.net, "If you don't need the power of regular expressions, you can choose faster (albeit simpler) alternatives like explode() or str_split()." php.net/manual/en/function.preg-split.php

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.