There is this String data from the column value of a table column : /var/www/imfmobile/photoj2meupload/7455575/photo32.png
I want to get the 7455575 and the photo32.png substring's. How to achieve that quickly ?
use explode to split the string at /:
$parts = explode('/',$mystring);
and then just use array_pop to get the values:
$filename = array_pop($parts);
$foldername = array_pop($parts);
$str = '/var/www/imfmobile/photoj2meupload/7455575/photo32.png';
$arr = explode('/', $str);
echo end($arr); // photo32.png
echo prev($arr); // 7455575
You might want to look at the pathinfo() and basename() functions:
$path_parts = pathinfo('/var/www/imfmobile/photoj2meupload/7455575/photo32.png');
echo basename( $path_parts['dirname'] ) . "\n";
echo $path_parts['basename'] . "\n";
Will output:
7455575
photo32.png
Related
I've been working with this code
<?php
class PerchTemplateFilter_sol_en_cat_path extends PerchTemplateFilter {
public function filterAfterProcessing($value, $valueIsMarkup = false) {
// ORIGINAL STRING: solutions-en/rail-technologies/track-components/name-of-product
$mystring = $value;
$replace = ['solutions-en', '%2F'];
$str = '';
$oldstr = str_replace($replace, $str, $mystring);
$str_to_insert = 'XXX';
$findme = '/';
$pos = strpos($mystring, $findme); // I NEED THIS TO INSERT $str_to_insert AFTER THE SECOND FORWARD SLASH FOUND IN THE ORIGINAL STRING?
$value = substr_replace($oldstr, $str_to_insert, $pos, 0);
return $value;
// $value: /rail-technologies/track-components/XXX/name-of-product
// Insert string at specified position
// https://stackoverflow.com/questions/8251426/insert-string-at-specified-position
}
}
PerchSystem::register_template_filter('sol_en_cat_path', 'PerchTemplateFilter_sol_en_cat_path');
?>
My string is: solutions-en/rail-technologies/track-components/name-of-product
I want to end up with: /rail-technologies/XXX/track-components/name-of-product
XXX is only a placeholder value
I guess I need to do something with $pos to set where I want XXX to be added to the string.
I need to insert after the second forward slash, as the string may contain different text
The code above outputs this string: /rail-technoXXXlogies/track-components/ewosr-switch-lock
I can't seem to figure out how to insert XXX after the second forward slash.
Hope someone can provide some help.
How about explode to array, then implode the first two items.
Join with xxx and implode the rest?
function AddInTheMiddle($start, $where, $what){
$arr = explode("/", $what);
$str = implode("/", array_splice($arr,$start,$where)) . '/xxx/' . implode("/", $arr);;
return $str;
}
$str = 'solutions-en/rail-technologies/track-components/name-of-product';
$str = AddInTheMiddle(1, 2, $str);
https://3v4l.org/m98io
Thank you Andreas, your post gave me the nudge I needed. I did this in the end.
// ORIGINAL $value: solutions-en/rail-technologies/track-components/name-of-product
$str = explode("/", $value);
$value = $str[1] . '/' . 'solutions' . '/' . $str[2] . '/';
return $value;
// Removed: solutions-en
// Added: solutions
// $value: rail-technologies/solutions/track-components/name-of-product
I was able to add the name-of-product to the end of the new string elsewhere in my template.
The following code is not
<?php
$deletinglist = addQuotes($_POST['delimglist']);
$deletelist = array($deletinglist);
foreach ($deletelist as $filename) {
unlink(dirname(__FILE__) . "/uploads/" . $filename);
}
function addQuotes($string) {
return '"'. implode('","', explode(',', $string)) .'"';
}
?>
Here $_POST['delimglist'] = "C0d49a7de7b635477125ffffa8df7b932.jpg,C0d49a7de7b635477125ffffa8df7b934.jpg,C0d49a7de7b635477125ffffa8df7b935.jpg";
If I use $deletelist = array("C0d49a7de7b635477125ffffa8df7b932.jpg","C0d49a7de7b635477125ffffa8df7b934.jpg","C0d49a7de7b635477125ffffa8df7b935.jpg");
Its working fine but if I use $deletelist = array($deletinglist); its not working.
I am getting the following Warning when trying to use like the above
Warning: unlink(/home/...somepath.../uploads/"C0d49a7de7b635477125ffffa8df7b932.jpg","C0d49a7de7b635477125ffffa8df7b934.jpg","C0d49a7de7b635477125ffffa8df7b935.jpg"): No such file or directory in /home/...somepath.../deletefile.php on line 9
I'm not sure why do you add quotes around filename?
The code should be as simple as this:
<?php
$deletelist = explode(',', $_POST['delimglist']);
foreach ($deletelist as $filename) {
unlink(dirname(__FILE__) . "/uploads/" . $filename);
}
?>
All you're doing is putting $deleteList into an array as a single element. You want to separate the values by ','. Use $deleteList = explode(',', $deleteList);
The following are not the same thing:
$arr1 = Array("a", "b", "c");
$str = "a,b,c";
$arr2 = Array($str);
The commas in the first example are a language construct: writing them inside a single variable does not mean they magically gain language construct abilities; inside the string they are just characters.
Similarly, this:
$str = "a,b,c";
foo($str);
is the same as this:
foo("a,b,c");
and not this:
foo("a", "b", "c");
You will have to use a function that explicitly splits up the string $_POST['delimglist']:
$deleteList = explode(',', $_POST['delimglist']);
I'm a newbie in PHP ,andnow I'm struck on this problem . I have a string like this :
$string = "qwe,asd,zxc,rty,fgh,vbn";
Now I want when user click to "qwe" it will remove "qwe," in $string
Ex:$string = "asd,zxc,rty,fgh,vbn";
Or remove "fhg,"
Ex:$string = "asd,zxc,rty,vbn";
I try to user str_replace but it just remove the string and still have a comma before the string like this:
$string = ",asd,zxc,rty,fgh,vbn";
Anyone can help? Thanks for reading
Try this out:
$break=explode(",",$string);
$new_array=array();
foreach($break as $newData)
{
if($newData!='qwe')
{
$new_array[]=$newData;
}
}
$newWord=implode(",",$new_array);
echo $newWord;
In order to achieve your objective, array is your best friend.
$string = "qwe,asd,zxc,rty,fgh,vbn";
$ExplodedString = explode( "," , $string ); //Explode them separated by comma
$itemToRemove = "asd";
foreach($ExplodedString as $key => $value){ //loop along the array
if( $itemToRemove == $value ){ //check if item to be removed exists in the array
unset($ExplodedString[$key]); //unset or remove is found
}
}
$NewLook = array_values($ExplodedString); //Re-index the array key
print_r($NewLook); //print the array content
$NewLookCombined = implode( "," , $NewLook);
print_r($NewLookCombined); //print the array content after combined back
here the solution
$string = "qwe,asd,zxc,rty,fgh,vbn";
$clickword = "vbn";
$exp = explode(",", $string);
$imp = implode(" ", $exp);
if(stripos($imp, $clickword) !== false) {
$var = str_replace($clickword," ", $imp);
}
$str = preg_replace('/\s\s+/',' ', $var);
$newexp = explode(" ", trim($str));
$newimp = implode(",", $newexp);
echo $newimp;
You could try preg_replace http://uk3.php.net/manual/en/function.preg-replace.php if you have the module set up. It will allow you to optionally replace trailing or leading commas easily:
preg_replace("/,*$providedString,*/i", '', "qwe,asd,zxc,rty,fgh,vbn");
This question already has answers here:
Strip off specific parameter from URL's querystring
(22 answers)
Closed 8 years ago.
I have to remove the last element in a string. I used rtrim in php but it is not working.
This is the string:
/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC
I need to remove "&make_order=ASC"
Can anyone help me?
$s = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo substr($s, 0, strrpos($s, '&'));
Edit:
$url = $base_url.trim( $_SERVER['REQUEST_URI'], "&year_order=".$arr['year_order']."" );
// ^
// |_ replace , with .
trim should work:
$string = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
$string = trim($string, "&make_order=ASC");
There's no guarantee that make_order will be at the end of the query string - or exist at all. To remove the field properly, you'd have to use something like this:
$url = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
// break down the URL into a path and query string
$parsed = parse_url($url);
// turn the query string into an array that we can manipulate
$qs = array();
parse_str($parsed['query'], $qs);
// remove the unwanted field
unset($qs['make_order']);
// rebuild the URL
$rebuilt = $parsed['path'];
if(!empty($qs)) {
$rebuilt .= '?' . http_build_query($qs);
}
echo $rebuilt;
$actual_link = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
echo str_replace("&make_order=ASC","",$actual_link);
$string = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
$args = array_pop(explode($string, "&"));
$string = implode("&", $args);
There are a bunch of ways. The easiest might be:
$i=strrpos($text,'&');
$newstring=substr($text,0,$i);
$str = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
echo $str . "<br>";
echo trim($str,"&make_order=ASC");
if &make_order=ASC is always going to be at the end, you can use strstr() to do this
$str = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo strstr($str,'&make_order=ASC',true);
Remove desired key from url.
Use:
$s = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo remove_key_from_url($url, 'make_order');
Output :
/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100
Code:
function remove_key_from_url($url, $key) {
if (strpos($url, '?') === false) return $url;
list($left, $right) = explode('?', $url, 2);
parse_str($right, $get);
if (isset($get[$key])) unset($get[$key]);
return $left . '?' . http_build_query($get);
}
I am new in PHP and can't figure out how to do this:
$link = 'http://www.domainname.com/folder1/folder2/folder3/folder4';
$domain_and_slash = http://www.domainname.com . '/';
$address_without_site_url = str_replace($domain_and_slash, '', $link);
foreach ($folder_adress) {
// function here for example
echo $folder_adress;
}
I can't figure out how to get the $folder_adress.
In the case above I want the function to echo these four:
folder1
folder1/folder2
folder1/folder2/folder3
folder1/folder2/folder3/folder4
The $link will have different amount of subfolders...
This gets you there. Some things you might explore more: explode, parse_url, trim. Taking a look at the docs of there functions gets you a better understanding how to handle url's and how the code below works.
$link = 'http://www.domainname.com/folder1/folder2/folder3/folder4';
$parts = parse_url($link);
$pathParts = explode('/', trim($parts['path'], '/'));
$buffer = "";
foreach ($pathParts as $part) {
$buffer .= $part.'/';
echo $buffer . PHP_EOL;
}
/*
Output:
folder1/
folder1/folder2/
folder1/folder2/folder3/
folder1/folder2/folder3/folder4/
*/
You should have a look on explode() function
array explode ( string $delimiter , string $string [, int $limit ] )
Returns an array of strings, each of
which is a substring of string formed
by splitting it on boundaries formed
by the string delimiter.
Use / as the delimiter.
This is what you are looking for:
$link = 'http://www.domainname.com/folder1/folder2/folder3/folder4';
$domain_and_slash = 'http://www.domainname.com' . '/';
$address_without_site_url = str_replace($domain_and_slash, '', $link);
// this splits the string into an array
$address_without_site_url_array = explode('/', $address_without_site_url);
$folder_adress = '';
// now we loop through the array we have and append each item to the string $folder_adress
foreach ($address_without_site_url_array as $item) {
// function here for example
$folder_adress .= $item.'/';
echo $folder_adress;
}
Hope that helps.
Try this:
$parts = explode("/", "folder1/folder2/folder3/folder4");
$base = "";
for($i=0;$i<count($parts);$i++){
$base .= ($base ? "/" : "") . $parts[$i];
echo $base . "<br/>";
}
I would use preg_match() for regular expression method:
$m = preg_match('%http://([.+?])/([.+?])/([.+?])/([.+?])/([.+?])/?%',$link)
// $m[1]: domain.ext
// $m[2]: folder1
// $m[3]: folder2
// $m[4]: folder3
// $m[5]: folder4
1) List approach: use split to get an array of folders, then concatenate them in a loop.
2) String approach: use strpos with an offset parameter which changes from 0 to 1 + last position where a slash was found, then use substr to extract the part of the folder string.
EDIT:
<?php
$folders = 'folder1/folder2/folder3/folder4';
function fn($folder) {
echo $folder, "\n";
}
echo "\narray approach\n";
$folder_array = split('/', $folders);
foreach ($folder_array as $folder) {
if ($result != '')
$result .= '/';
$result .= $folder;
fn($result);
}
echo "\nstring approach\n";
$pos = 0;
while ($pos = strpos($folders, '/', $pos)) {
fn(substr($folders, 0, $pos++));
}
fn($folders);
?>
If I had time, I could do a cleaner job. But this works and gets across come ideas: http://codepad.org/ITJVCccT
Use parse_url, trim, explode, array_pop, and implode