I have a question which relates to PHP. Is there any way to just grab the last string using a delimiter?
For example, to put you in perspective, I want to grab the lastest content from the / from every string.
/folder1/blabla/important
/folder2/blabla/blabla/bla/important2
How could I using PHP cut the whole string and get only the latest value. The output would be something like:
/important
/important2
I have tried regex but I am not very good at it,
MY CODE:
$var = 'goldfe/sfksfksk/admadmadmam/akdmasdkasm/red';
echo $var . '<br>';
$varPretty = explode('/', $var);
echo $varPretty[-1];
Here the $varPretty[-1] should return red.
ANOTHER SOLUTION IS:
$var = 'goldfe/sfksfksk/admadmadmam/akdmasdkasm/red';
echo $var . '<br>';
$varPretty = explode('/', $var);
echo end($varPretty);
Please try this method will work for you:
$txt = "/folder1/blabla/important";
echo substr($txt, strrpos($txt, '/') + 1);
Output should be like:
important
Related
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)];
I am having a problem a problem with retrieving parenthesis value from url. I am developing a PHP project using CodeIgniter Framework.
I have a mvc url format like this - http://localhost/controller/action/id/name
Then I passed the value like this - http://localhost/controller/action/2/test%20(test)
And like this as well - Then I passed the value like this:
http://localhost/controller/action/2/test+(test)
So my action function is like this with parameters-
function action($id,$name)
{
$name = urldecode($name)
//I find the index of start "t"
echo strpos($name,'t'); //this is working find
echo strpos($name,'('); // this is outputing nothing
echo $name; // this is outputing test (test)
}
What is the problem ? Why cannot I find index of "(". Actually I and retrieving record from database using that value. But parenthesis is not working well with php. I showing output correctly. But cannot find index of it.
Finally I found the solution. That is the issue with Codeigniter Framework. I replaced all "(" and ")" with "[" and "]" before urlencoding. Then I replaced all "[" and "]" with "(" and ")" after urldecoding. You will get the answer after you read this article. http://qubitlogs.com/PHP/2013/01/24/parentheses-in-urls-not-working-codeigniter-datamapper-orm/ . Thank everyone for helping me.
Try like this with preg_match:
<?php
preg_match('/\((.*?)\)/',urldecode($name),$a);
echo $a[1];
Try this
<?php
$url = 'localhost/melomap_music/singers/details/760/test%20(test)';
$string = urldecode($url);
$pattern1 = '/[)]/';
$pattern2 = '/[(]/';
preg_match($pattern1, $string, $matches, PREG_OFFSET_CAPTURE);
preg_match($pattern2, $string, $matches2, PREG_OFFSET_CAPTURE);
$start = $matches2[0][1]; //49
$end = $matches[0][1]; //54
?>
I'm a newbie with programming; now, I have some problems with PHP programing.
I want to extract the URL from the following string:
"success":true,"load":"http:\/\/8.88.88.8\/list\/si3diwoe\/123","Live":true
The desired string is
http://8.88.88.8/list/si3diwoe/123
Can anyone tell me how this work in code?
Thank you very much!
$string = '"success":true,"load":"http:\/\/8.88.88.8\/list\/si3diwoe\/123","Live":true';
// The JSON way
$array = json_decode('{' . $string . '}'); // Wrap in {} to make object
$url = $array->load;
echo "Using JSON : $url", PHP_EOL;
// The RegEx way
preg_match('/load":"(.*?)"/', $string, $matches);
$url = stripslashes($matches[1]);
echo "Using RegEx: $url", PHP_EOL;
Output:
Using JSON : http://8.88.88.8/list/si3diwoe/123
Using RegEx: http://8.88.88.8/list/si3diwoe/123
If it's a json string, you can use json_decode to assign it to a variable, say $arr, then stripslashes($arr['load']);
if it's not, you can use explode("," , $string), and assign it to a variable, say $arr again. Run explode again (explode(":", $arr[1])) and assigned it to another variable, say $ar, then do stripslashes on $ar['1'];
hi all i am trying to parse a big string and want to obtain only the value of id(id=dfsdfdsfdsfsaddfdfdfd) . My current code output extra data beyon the id value. could any one help me fix this problem.Thanks
preg_match_all("#live3.me.somesite.com([^<]+)\"#", $html, $foo);
print_r($foo[0]);
sample input string:
$html=".............."url":"rtmp:\/\/live3.me.somesite.com\/live\/?id=dfsdfdsfdsfsaddfdfdfd","name":"8.low.stream".........";
Is this an issue where you are set on using preg_match?
Or would something like 'parse_url' be acceptable?
http://php.net/manual/en/function.parse-url.php
Once parsed, getting specific query string parameters out should be easy
Just for the fun of answering an 8 month old question, here is my go at it :-)
We have got this to work with:
$html='".............."url":"rtmp:\/\/live3.me.somesite.com\/live\/?id=dfsdfdsfdsfsaddfdfdfd","name":"8.low.stream"........."';
That string sure looks a bit JSONish to me, so why not ...
// 1. Get rid of leading and trailing quotes and dots
$clean = trim($html, '"');
$clean = trim($clean, '.');
// 2. Add squiggly brackets to form a JSON string
$json = '{' . $clean . '}';
// 3. Decode the JSON into an array
$array = json_decode($json, true);
// 4. Parse URL value from the array and grab the query part
$query = parse_url($array['url'], PHP_URL_QUERY);
// 5. Get parameter values from the query
parse_str($query, $params);
// 6. Ta-da!
echo "Readable : ", $params['id'], PHP_EOL;
And of course ...
// The one-liner!
parse_str(parse_url(json_decode('{'.trim(trim($html,'"'),'.').'}', true)['url'], PHP_URL_QUERY), $params2);
echo "One-liner: ", $params2['id'], PHP_EOL;
Output:
Readable : dfsdfdsfdsfsaddfdfdfd
One-liner: dfsdfdsfdsfsaddfdfdfd
I want to be able to specify an index in a string and remove it.
I have the following:
"Hello World!!"
I want to remove the 4th index (o in Hello). Here would be the end result:
"Hell World!!"
I've tried unset(), but that hasn't worked. I've Googled how to do this and that's what everyone says, but it hasn't worked for me. Maybe I wasn't using it right, idk.
This is a generic way to solve it:
$str = "Hello world";
$i = 4;
echo substr_replace($str, '', $i, 1);
Basically, replace the part of the string before from the index onwards with the part of the string that's adjacent.
See also: substr_replace()
Or, simply:
substr($str, 0, $i) . substr($str, $i + 1)
$str="Hello World";
$str1 = substr($str,0,4);
$str2 = substr($str,5,7);
echo $str1.$str2;
This php specific of working with strings also bugged me for a while. Of course natural solution is to use string functions or use arrays but this is slower than directly working with string index in my opinion. With the following snippet issue is that in memory string is only replaced with empty � and if you have comparison or something else this is not good option. Maybe in future version we will get built in function to remove string indexes directly who knows.
$string = 'abcdefg';
$string[3] = '';
var_dump($string);
echo $string;
$myVar = "Hello World!!";
$myArray = str_split($myVar);
array_splice($myArray, 4, 1);
$myVar = implode("", $myArray);
Personal I like dealing with arrays.
(Sorry about lack of code brackets putting this up via my phone)
I think can create a function and call it like this
function rem_inx ($str, $ind)
{
return substr($str,0,$ind++). substr($str,$ind);
}
//use
echo rem_inx ("Hello World!!", 4);