0

I've got a URL, say, $url='https://www.myurl.com/monkey-48-chicken-broccoli-ham.html'. I want to take the path and split the end into two variables: one containing the number (48), and one containing everything after the number (chicken-broccoli-ham).

While I can divide the returned array from my code below into separate words, the problem is, I don't know how many words will be after the number.

So my question is, how do I split the path into "number" and "everything after number" to store those as variables? Here's what I have so far:

$url='https://www.myurl.com/monkey-48-chicken-broccoli-ham.html';
$parsedUrl = parse_url($url);
$path = parse_url($url, PHP_URL_PATH);
$parts = explode('/', $path);
$tag = end($parts);
$tag1 = str_replace("-", " ", $tag);  //replace - with spaces
$tag2 = str_replace(".html", "", $tag1);//delete the ".html" off the end
$tag3 = str_replace("monkey", "", $tag2); //delete the "monkey" word.

here's where I need help:

$number = ???;
$wordstring = ???;
2
  • So you want the result to be as [48, chicken broccoli ham] or [monkey 48, chicken broccoli ham] ? Commented Jun 17, 2013 at 16:30
  • thanks result as 48, chicken broccoli ham Commented Jun 17, 2013 at 16:34

3 Answers 3

1
$url='https://www.myurl.com/monkey-48-chicken-broccoli-ham.html';
preg_match("/([0-9]+)[-](.+)\.html$/",$url,$matches);

$matches[1] contains the number

$matches[2] contains "chicken-broccoli-ham"

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

<?php

$url = 'https://www.myurl.com/monkey-48-chicken-broccoli-ham.html';
$path = basename($url, ".html");
$path = str_replace("-", " ", $path);
preg_match("/(\d+)\s+(.*)/", $path, $match);

echo $match[1] // 48 (number)
echo $match[2] // word after number (chicken broccoli ham)

?>

1 Comment

fantastic thank you. I knew this was an easy one. I obviously missed the preg_match in the manual!
0
<?php

$url = 'https://www.myurl.com/monkey-48-chicken-broccoli-ham.html';
$path = parse_url($url, PHP_URL_PATH);
$parts = preg_split('/[0-9]+/', $path);

with parse_url you get the path part of your url (monkey-48-chicken-broccoli-ham.html) then simply split the string by the number.

Note: you need to remove the - of the beginning and the .html of the end to achieve your desired result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.