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));
Related
Substr PHP
I have a string like http://domain.sf/app_local.php/foo/bar/33.
The last characters are the id of an element. Its length could be more than one, so I can not use:
substr($dynamicstring, -1);
In this case, it must be:
substr($dynamicstring, -2);
How can I get the characters after "/bar/" on the string without depending on the length?
To ensure you are getting an immediate section after the bar, use regular expressions:
preg_match('~/bar/([^/?&#]+)~', $url, $matches);
echo $matches[1]; // 33
You can use explode(), like this:
$id = explode('/',$var);
And take the element where you had the id.
You could use explode('/', $dynamicstring) to split the string into an array of the strings inbetween each /. Then you could use end() on the result of this to get the last part.
$id = end(explode('/', $dynamicstring));
Try this:
$dynamicstring = 'http://domain.sf/app_local.php/foo/bar/33';
// split your string into an array with /
$parts = explode('/', $dynamicstring);
// move the array pointer to the end
end($parts);
// return the current position/value of the $parts array
$id = current($parts);
// reset the array pointer to the beginning => 0
// if you want to do any further handling
reset($parts);
echo $id;
// $id => 33
Test it yourself here.
You can use a regular expression to do it:
$dynamicstring = "http://domain.sf/app_local.php/foo/bar/33";
if (preg_match('#/([0-9]+)$#', $dynamicstring, $m)) {
echo $m[1];
}
I tested it out myself before answering. Other answers are reasonable too, but this will work according to your need...
<?php
$url = "http://domain.sf/app_local.php/foo/bar/33";
$id = substr($url, strpos($url, "/bar/") + 5);
echo $id;
Please find the below answer.
$str = "http://domain.sf/app_local.php/foo/bar/33";
$splitArr = explode('/', explode('//', $str)[1]);
var_dump($splitArr[count($splitArr)-1]);
I have a large string and want to extract data between .ism and the slash / before it. For example I want to get: life-episode-galaxy
My current code gives all data before .ism. Could anyone tell me what is wrong here and how to get only data between .ism and slash / before it?
<?
$code="media=http://somesite.com/4534543kjlkljklkjlkkljlkdsfsfo/life-episode-galaxy.ism/manifest,deliverymethod=adaptiv";
$startsAt3 = strpos($code, "/") + strlen("/");
$endsAt3 = strpos($code, ".ism", $startsAt3);
$result3 = substr($code, $startsAt3, $endsAt3 - $startsAt3);
echo $result3;
?>
I Assume your link would have always the same number of slashes / you can just explode into an array and output the right element, removing the not needed data with str_replace
$code="media=http://somesite.com/4534543kjlkljklkjlkkljlkdsfsfo/life-episode-galaxy.ism/manifest,deliverymethod=adaptiv";
$array = explode("/", str_replace("//", "/", $code));
echo str_replace('.ism', '', $array[3]);
This will output
life-episode-galaxy
Live Sample
You could use a regexp, but that's boring.
You can use strrpos with the 3rd offset parameter, using a negative offset.
$ism_pos = strpos($code, ".ism");
$last_slash_pos_before_ism = strrpos($code, "/", $ism_pos - strlen($code));
$result = substr($code, $last_slash_pos_before_ism, $ism_pos);
Might be off-by-one here and there, check it.
I would use regex:
$pattern = '#/(.*)\.ism/#U';
$matches = array();
$found = preg_match($pattern, $string, $matches);
if (1 === $found) {
$your_desired_string = $matches[1];
} else {
// not found
}
How can I use str_replace method for replacing a specified portion(between two substrings).
For example,
string1="www.example.com?test=abc&var=55";
string2="www.example.com?test=xyz&var=55";
I want to replace the string between '?------&' in the url with ?res=pqrs&. Are there any other methods available?
You could use preg_replace to do that, but is that really what you are trying to do here?
$str = preg_replace('/\?.*?&/', '?', $input);
If the question is really "I want to remove the test parameter from the query string" then a more robust alternative would be to use some string manipulation, parse_url or parse_str and http_build_query instead:
list($path, $query) = explode('?', $input, 2);
parse_str($query, $parameters);
unset($parameters['test']);
$str = $path.'?'.http_build_query($parameters);
Since you're working with URL's, you can decompose the URL first, remove what you need and put it back together like so:
$string1="www.example.com?test=abc&var=55";
// fetch the part after ?
$qs = parse_url($string1, PHP_URL_QUERY);
// turn it into an associative array
parse_str($qs, $a);
unset($a['test']); // remove test=abc
$a['res'] = 'pqrs'; // add res=pqrs
// put it back together
echo substr($string1, 0, -strlen($qs)) . http_build_query($a);
There's probably a few gotchas here and there; you may want to cater for edge cases, etc. but this works on the given inputs.
Dirty version:
$start = strpos($string1, '?');
$end = strpos($string1, '&');
echo substr($string1, 0, $start+1) . '--replace--' . substr($string1, $end);
Better:
preg_replace('/\?[^&]+&/', '?--replace--&', $string1);
Depending on whether you want to keep the ? and &, the regex can be mofidied, but it would be quicker to repeat them in the replaced string.
Think of regex
<?php
$string = 'www.example.com?test=abc&var=55';
$pattern = '/(.*)\?.*&(.*)/i';
$replacement = '$1$2';
$replaced = preg_replace($pattern, $replacement, $string);
?>
I've got this string, but I need to remove specific things out of it...
Original String: hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64.
The string I need: sh-290-92.ch-215-84.lg-280-64.
I need to remove hr-165-34. and hd-180-1.
!
EDIT: Ahh ive hit a snag!
the string always changes, so the bits i need to remove like "hr-165-34." always change, it will always be "hr-SOMETHING-SOMETHING."
So the methods im using wont work!
Thanks
Depends on why you want to remove exactly those Substrigs...
If you always want to remove exactly those substrings, you can use str_replace
If you always want to remove the characters at the same position, you can use substr
If you always want to remove substrings between two dots, that match certain criteria, you can use preg_replace
$str = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
$new_str = str_replace(array('hr-165-34.', 'hd-180-1.'), '', $str);
Info on str_replace.
The easiest and quickest way of doing this is to use str_replace
$ostr = "hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64";
$nstr = str_replace("hr-165-34.","",$ostr);
$nstr = str_replace("hd-180-1.","",$nstr);
<?php
$string = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
// define all strings to delete is easier by using an array
$delete_substrings = array('hr-165-34.', 'hd-180-1.');
$string = str_replace($delete_substrings, '', $string);
assert('$string == "sh-290-92.ch-215-84.lg-280-64" /* Expected result: string = "sh-290-92.ch-215-84.lg-280-64" */');
?>
Ive figured it out!
$figure = $q['figure']; // hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64
$s = $figure;
$matches = array();
$t = preg_match('/hr(.*?)\./s', $s, $matches);
$s = $figure;
$matches2 = array();
$t = preg_match('/hd(.*?)\./s', $s, $matches2);
$s = $figure;
$matches3 = array();
$t = preg_match('/ea(.*?)\./s', $s, $matches3);
$str = $figure;
$new_str = str_replace(array($matches[0], $matches2[0], $matches3[0]), '', $str);
echo($new_str);
Thanks guys!
I would like to split a string at the first line break, instead of the first blank line
'/^(.*?)\r?\n\r?\n(.*)/s' (first blank line)
So for instance, if I have:
$str = '2099 test\nAre you sure you
want to continue\n some other string
here...';
match[1] = '2099 test'
match[2] = 'Are you sure you want to continue\n some other string here...'
preg_split() has a limit parameter you can take to your advantage. You could just simply do:
$lines = preg_split('/\r\n|\r|\n/', $str, 2);
<?php
$str = "2099 test\nAre you sure you want to continue\n some other string here...";
$match = explode("\n",$str, 2);
print_r($match);
?>
returns
Array
(
[0] => 2099 test
[1] => Are you sure you want to continue
some other string here...
)
explode's last parameter is the number of elements you want to split the string into.
Normally just remove on \r?\n:
'/^(.*?)\r?\n(.*)/s'
You can use preg_split as:
$arr = preg_split("/\r?\n/",$str,2);
See it on Ideone
First line break:
$match = preg_split('/\R/', $str, 2);
First blank line:
$match = preg_split('/\R\R/', $str, 2);
Handles all the various ways of doing line breaks.
Also there was a question about splitting on the 2nd line break. Here is my implementation (maybe not most efficient... also note it replaces some line breaks with PHP_EOL)
function split_at_nth_line_break($str, $n = 1) {
$match = preg_split('/\R/', $str, $n+1);
if (count($match) === $n+1) {
$rest = array_pop($match);
}
$match = array(implode(PHP_EOL, $match));
if (isset($rest)) {
$match[] = $rest;
}
return $match;
}
$match = split_at_nth_line_break($str, 2);
Maybe you don't even need to use regex's. To get just split lines, see:
What's the simplest way to return the first line of a multi-line string in Perl?