Dennis
Dennis

Reputation: 147

Get the last string of URL's

I am getting data from a page like this:

<?php $speaker = $page->uri();
  $speakerEvents = page('program')->grandchildren()->filter(function($child) use($speaker) {
  $speakers = $child->speaker()->toStructure();
  return $speakers->findBy('selectspeaker', $speaker);
});

echo $speakerEvents;                

?>

It's output is:

"page/page/pageIWant
page/page/pageIWant"

The Result I want is

pageIWant
pageIWant

I tried to get the last name with

echo basename($speakerEvents);

But I only get one of the last pageIWant

How do I get the last pages without removing the first URL?

Upvotes: 1

Views: 288

Answers (3)

Pinke Helga
Pinke Helga

Reputation: 6682

Your string has a line break as path separator. You need to split lines by either \r\n (CR-LF), \n, or \r which can be done with preg_split. If you can ensure one of the formats, you can also use the simple explode function.

foreach (preg_split('~(?:\r?\n|\r)~u', $speakerEvents) as $path)
  echo basename($path) , PHP_EOL;

As AbraCadaver noted, you can add the flag PREG_SPLIT_NO_EMPTY to preg_split if you do not want empty lines to be handled.

If the double qoutes you show in the question are part of the string, you need further more to trim the string:

foreach (preg_split('~(?:\r?\n|\r)~u', trim($speakerEvents, '"')) as $path)
  echo basename($path) , PHP_EOL;

Upvotes: 2

user5283119
user5283119

Reputation:

You can explode the string e.g.

$array = explode('/', 'page/page/pageIWant');

Then you can retrieve it using the index like so:

$array[(count($array) - 1)];

Upvotes: 1

Googlian
Googlian

Reputation: 6723

Use the explode method to get array of URL

<?php
    $link = $_SERVER['PHP_SELF'];
    $link_array = explode('/',$link);
    echo $page = end($link_array);
?>

If your output is

page/page/pageIWant
page/page/pageIWant

<?php
    $text = "page/page/pageIWant";
    $text_arr = explode('/',$text);
    echo $page = end($text_arr);
    // this will print: pageIWant
?>

Upvotes: 2

Related Questions