Get the last string of URL's - php

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?

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
?>

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;

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)];

Related

how to remove the first part of a path in php?

i have a path like this:
/dude/stuff/lol/bruh.jpg
i want to echo it like this:
/stuff/lol/bruh.jpg
how to do this? and if you could please explain it. i found one good answer
Removing part of path in php but i cannot work my way around with explode and implode.
please give me the link to the duplicate answer if my question is a duplicate
You could use strpos with substr:
$string = '/dude/stuff/lol/bruh.jpg';
$string = substr($string, strpos($string, '/', 1));
The strpos to look for the position of the / after the first one, then use substr to get the string starting from that position till the end.
$path = '/dude/stuff/lol/bruh.jpg';
$path = explode('/', $path);
unset($path[1]);
$path = implode('/', $path);
Will separate the string into an array, then unset the first item (technically the second in the array, since the first element will be empty due to the string starting with /). Finally the path is imploded, and you get:
/stuff/lol/bruh.jpg
Try this :
$string = "/dude/stuff/lol/bruh.jpg";
$firstslash = strpos($string,"/",1);
$secondstring = substr($string, $firstslash+1);
echo "String : " . $string;
echo " <br> Result : " . $secondstring;
You can use a regular expression to extract resource name you need.
preg_match('/(?P<name>[^\/]+)$/', $path, $match);
Then you have to use $match as array, and you can see the name inside of it.
$match['name];

Remove last character from a string [duplicate]

This question already has answers here:
How do I remove all specific characters at the end of a string in PHP?
(10 answers)
Closed 12 months ago.
I have a list of country as an array .. i want this array in following format to later return it via ajax :-
"india","usa","uk" ..
Used following code to get somewhat i was looking for ..
foreach($country_list as $country) {
$countries .= '"'.$country['label'].'",';
}
problem is it is giving output like "india","usa","uk", ... i.e with trailing comma .
Tried to remove it with
substr_replace($countries, "0", -1);
and
rtrim($countries, ",");
But didnt work ! .. Please help !
I think that you're missing to assign the variable back after the trim:
$s = '"india","usa","uk",';
$s = rtrim($s, ',');
// prints "india","usa","uk"
print $s;
Demo
Try before buy
try this substr() or mb_substr()
substr($string, 0, -1);
mb_substr($string, 0, -1);
or check this link
Have you tried using: str_replace(",", " ", $countries);
This function should replace each occurence of a comma with a space.
if (strlen($b) > 1){
$b = substr($b,0, -1);
}
Try this
$countries = [];
foreach($country_list as $country) {
$countries[] = $country['label'];
}
$new_array = implode(",", $countries);
Use implode instead:
$arr = array();
foreach($country_list as $country)
array_push($arr, $country['label']);
$comma_separated = implode(",", $arr);
Try this
create a variable ($comsep) and initialise it to an empty string.
in the foreach loop concatenate the variable ($comsep) at the start of the string.
add an extra statement in the foreach loop to set the variable ($comsep) to the value "," - after the concatenation statement.
This will put a comma at the start of each appended string except for the first one. The is no longer a trailing comma to deal with so no need to try trimming it off.
// Try to use chop() function in php. It helps in removing last character from a string
<?php
echo '<br>' .$country_name = "'USA','UK','India',";
echo '<br>' .chop($country_name,",");
exit;
?>
Output : 'USA','UK','India'
foreach($country_list as $country) {
$countries[] = $country['label'];
}
json_encode($countries);

PHP find a string and get corresponding data

have this text
"Number":"X0011","Name":"aaaaaaaaaaaaaa","Adress":"12345","Phone":"56976585","Number":"X0044","Name":"bbbbbbbbbbbbbbbbbbb","Adress":"786487647","Phone":"34214234",.......
And want to return with PHP something like this (just names and codes, and ignore all others fields)
Number:X0011
Name:aaaaaaaaaaaaaa
Number:X0044
Name:bbbbbbbbbbbbbbbbbbb
....
Thanks in advance
You can do that with the explode function
========
explode function
$mystring = ""Number":"X0011","Name":"aaaaaaaaaaaaaa","Adress":"12345","Phone":"56976585";
$pieces = explode(",", $mystring);
echo $pieces[0]; // Number:X0011
echo $pieces[1]; // Name:aaaaaaa
The following code will allow you to cycle through all of the items and get at the individual values $temp_str[1] will contain the actual value of that item. It also means that you can keep adding info to the of the string and this code will parse it.
$str = '"Number":"X0011","Name":"aaaaaaaaaaaaaa","Adress":"12345","Phone":"56976585"';
$str = str_replace('"',"",$str); // remove the double quotes
$pieces = explode(",", $str);
foreach($pieces as $piece){
$temp_str = explode(',',$piece);
echo $temp_str[0]; // 'Number:'X0011 // gives the heading
echo $temp_str[1]; // Name:'aaaaaaa' // gives the value
echo "<br />";
}

Removing last part of string divided by a colon

I have a string that looks a little like this, world:region:bash
It divides folder names, so i can create a path for FTP functions.
However, i need at some points to be able to remove the last part of the string, so, for example
I have this world:region:bash
I need to get this world:region
The script wont be able to know what the folder names are, so some how it needs to be able to remove the string after the last colon.
$res=substr($input,0,strrpos($input,':'));
I should probably highlight that strrpos not strpos finds last occurrence of a substring in given string
$tokens = explode(':', $string); // split string on :
array_pop($tokens); // get rid of last element
$newString = implode(':', $tokens); // wrap back
You may want to try something like this:
<?php
$variable = "world:region:bash";
$colpos = strrpos($variable, ":");
$result = substr($variable, 0, $colpos);
echo $result;
?>
Or... if you create a function using this information, you get this:
<?php
function StrRemoveLastPart($string, $delimiter)
{
$lastdelpos = strrpos($string, $delimiter);
$result = substr($string, 0, $lastdelpos);
return $result;
}
$variable = "world:region:bash";
$result = StrRemoveLastPart($variable, ":");
?>
Explode the string, and remove the last element.
If you need the string again, use implode.
$items = array_pop(explode(':', $the_path));
$shotpath = implode(':', $items);
Use regular expression /:[^:]+$/, preg_replace
$s = "world:region:bash";
$p = "/:[^:]+$/";
$r = '';
echo preg_replace($p, $r, $s);
demo
Notice how $ which means string termination, is made use of.
<?php
$string = 'world:region:bash';
$string = implode(':', explode(':', $string, -1));

php preg_replace words last part

$str='<p>http://domain.com/1.html?u=1234576</p><p>http://domain.com/2.html?u=2345678</p><p>http://domain.com/3.html?u=3456789</p><p>http://domain.com/4.html?u=56789</p>';
$str = preg_replace('/.html\?(.*?)/','.html',$str);
echo $str;
I need get
<p>http://domain.com/1.html</p>
<p>http://domain.com/2.html</p>
<p>http://domain.com/3.html</p>
<p>http://domain.com/4.html</p>
remove ?u=*number* from every words last part. thanks.
Change this line:
$str = preg_replace('/.html\?(.*?)/','.html',$str);
into this:
$str = preg_replace('/.html\?(.*?)</','.html<',$str);
An alternative to the other answers:
preg_replace("/<p>([^?]*)\?[^<]*<\/p>/", "<p>$1</p>", $input);
This will match all types of urls with url variables, not only the ones with html-files in them.
For example, you can also extract these types of values:
<p>http://domain.com/1.php?u=1234576</p>
<p>http://domain.com?u=1234576</p>
<p>http://domain.com</p>
<p>http://domain.com/pages/users?uid=123</p>
With an output of:
<p>http://domain.com/1.php</p>
<p>http://domain.com</p>
<p>http://domain.com</p>
<p>http://domain.com/pages/users</p>
This code will load the url's into an array so they can be handled on the fly:
$str = '<p>http://domain.com/1.html?u=1234576</p><p>http://domain.com/2.html?u=2345678</p><p>http://domain.com/3.html?u=3456789</p><p>http://domain.com/4.html?u=56789</p>';
$str = str_replace("<p>","",$str);
$links = preg_split('`\?.*?</p>`', $str,-1,PREG_SPLIT_NO_EMPTY);
foreach($links as $v) {
echo "<p>".$v."</p>";
}

Categories