PHP: extract name from string - php

I have a path that looks like:
/home/duke/aa/servers/**servername**/var/...morefiles...
With php, I want to extract the "servername" from the path
Unfortunately I'm not that well versed with php but I came up with something that used strstr() but I am only using PHP version 5.2 where as one of the parameter functions require 5.3
What could be some code that would return "servername"?

you can use explode('/', $path) to break it down into the individual directories. After that, it's up to you to figure out which array element is the server name (with your sample path, it'd be #4):
$parts = explode('/', $path);
echo $parts[4]; // **servername**

function getServerName($data) {
preg_match('#/servers/(.+)/var/#', $data, $result);
if (isset($result[1]) {
return $result[1];
}
}
$data = '/home/duke/aa/servers/**servername**/var/...morefiles...';
echo getServerName($data);

$str = '/home/duke/aa/servers/**servername**/var/...morefiles...';
echo preg_replace('$(.+)/servers/(.+)/var/(.+)$', '\2', $str);

Related

PHP regex for image name with numbers

I have images with names such as:
img-300x300.jpg
img1-250x270.jpg
These names will be stored in a string variable. My image is in Wordpress so it will be located at e.g.
mywebsite.com/wp-content/uploads/2012/11/img-300x300.jpg
and I need the string to be changed to
mywebsite.com/wp-content/uploads/2012/11/img.jpg
I need a PHP regular expression which would return img.jpg and img1.jpg as the names.
How do I do this?
Thanks
Addition
Sorry guys, I had tried this but it didn't work
$string = 'img-300x300.jpg'
$pattern = '[^0-9\.]-[^0-9\.]';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
You can do this using PHP native functions itself.
<?php
function genLink($imagelink)
{
$img1 = basename($imagelink);
$img = substr($img1,0,strrpos($img1,'-')).substr($img1,strpos($img1,'.'));
$modifiedlink = substr($imagelink,0,strrpos($imagelink,'/'))."/".$img;
return $modifiedlink;
}
echo genLink('mywebsite.com/wp-content/uploads/2012/11/flower-img-color-300x300.jpg');
OUTPUT :
mywebsite.com/wp-content/uploads/2012/11/flower-img-color.jpg
You can do that as:
(img\d*)-([^.]*)(\..*)
and \1\3 will contain what you want:
Demo: http://regex101.com/r/vU2mD4
Or, replace (img\d*)-([^.]*)(\..*) with \1\3
May be this?
(\w+)-[^.]+?(\.\w+)
The $1$2 will give you what you want.
search : \-[^.]+
replace with : ''
(.[^\-]*)(?:.[^\.]*)\.(.*)
group 1 - name before "-"
group 2 - extension. (everything after ".")
As long as there is only one - and one . then explode() should work great for this:
<?php
// array of image names
$images = array();
$images[] = 'img-300x300.jpg';
$images[] = 'img1-250x270.jpg';
// array to store new image names
$new_names = array();
// loop through images
foreach($images as $v)
{
// explode on dashes
// so we would have something like:
// $explode1[0] = 'img';
// $explode1[1] = '300x300.jpg';
$explode1 = explode('-',$v);
// explode the second piece on the period
// so we have:
// $explode2[0] = '300x300';
// $explode2[1] = 'jpg';
$explode2 = explode('.',$explode1[1]);
// now bring it all together
// this translates to
// img.jpg and img1.jpg
$new_names[] = $explode1[0].'.'.$explode2[1];
}
echo '<pre>'.print_r($new_names, true).'</pre>';
?>
That's an interesting question, and since you are using php, it can be nicely solved with a branch reset (a feature of Perl, PCRE and a few other engines).
Search: img(?|(\d+)-\d{3}x\d{3}|-\d{3}x\d{3})\.jpg
Replace: img\1.jpg
The benefit of this solution, compared with a vague replacement, is that we are sure that we are matching a file whose name matches the format you specified.

isolate the number exists at the end of the URI php

I have the following URI:
/belt/belts/fk/product/40P35871
And I want to retrieve the last content after the last /.
In this case is 40P35871.
How can I do this?
How about explode?
$elements = explode('/', $input);
$productId = end($elements);
Here's a different solution entirely. (and the simplest!)
Using basename
$var = "/belt/belts/fk/product/40P35871";
echo basename($var);
Output:
40P35871
You don't need regex for something simple like that. Consider using strrchr, documentation here
$lastcontent = substr(strrchr($uri, "/"), 1);
Considering this special case of $uri being a path, the best answer would be the one provided by Chtulhu.
basename will return the last part of a path, documentation here
$lastcontent = basename($uri);
Just like this
$str = '/belt/belts/fk/product/40P35871';
$arr = explode('/', $str);
$var = array_pop($arr);
var_dump($var);
or
$var = substr($str, strrpos($str,'/') + 1);
Try this
$result = preg_replace('%(/(?:[^/]+?/)+)([^/]+)\b%', '$2', $subject);
use this:
echo preg_replace('/[a-z0-9]$/i', '$1', $url);
this will give you the last position
note: but on this url only, query strings make this useless and use need to parse the url for the same first for this to work
Don't use regex. In this case you can act as the follow
myUrl = $_SERVER[REQUEST_URL];
$number = substr(strrpos(myUri,'/')+1);
You don't need regex.
Find the last content and get it using substr():
$lastcontent = substr(strrchr($uri, "/"), 1);

Is there a more efficient way to perform this instead of using explode/implode?

This simple PHP function accepts a URL string and returns the directory:
function getDirFromFilePath($file) {
$temp = explode('/', $file);
array_pop($temp);
return implode('/', $temp);
}
Example:
Input: http://www.domain.com/directory/filename.jpg
Output: http://www.domain.com/directory
Just wondering if there is a more efficient way to perform this, perhaps like a regex would?
You can just use dirname(), which works with URLs too:
dirname('http://www.domain.com/directory/filename.jpg')

Need to get middle part of path

I have a path like this
apples/oranges/bananas
I need to get the middle item in the path, in this case oranges.
What is the best way to do it? I can do it myself using strpos and substr but I imagine there is a better way...
$path = explode("/", "apples/oranges/bananas");
echo $path[1];
You could explode the string (assuming it is) and then get the correct index from the array. Like so:
$string = "apples/oranges/bananas";
$array = explode('/', $string);
echo $array[1]; //outputs oranges
Just to show off array dereferencing in PHP > 5.4:
echo explode('/', 'apple/oranges/bananas')[1];
If
$path = 'apples/oranges/bananas';
you could do:
$dir = basename(dirname($path));
if you want to start from the end of the string, and should work on Windows, or
$dir = preg_match('|/([^/]*)|', $path, $m) ? $m[1] : false;
if you want to start at the beginning of the string, and will not work on Windows.
Is it always 3 words separated by 2 slashes?
if yes, you can try:
$mypath = explode('/', 'apple/oranges/bananas');
echo $mypath[1]; //gives oranges

Removing part of path in php

I have a path like:
$path='somefolder/foo/bar/lastdir';
and I want to remove the last part, so I have:
$path='somefolder/foo/bar';
Like I went one folder up.
I'm really newbie in php, maybe its just one function, although I can't find it anywhere.
You could try this (tested and works as expected):
$path = 'somefolder/foo/haha/lastone';
$parts = explode('/', $path);
array_pop($parts);
$newpath = implode('/', $parts);
$newpath would now contain somefolder/foo/haha.
use :
dirname(dirname('somefolder/foo/haha/lastone/somescript.php'));
this should return:
somefolder/foo/haha/
This is untested, but try:
$path_array = explode('/',$path);
array_pop($path_array);
$path = implode('/',$path_array);
If you are currently at:
somefolder/foo/haha/lastone/somescript.php
and you want to access:
somefolder/foo/haha/someotherscript.php
just type:
../someotherscript.php
Probably using a regex function would be appropriate if the last part is going to vary. Try
$pattern = '#/.*$#U';
$stripped_path = preg_replace($pattern, '', $original_path);
This will strip everything off the original path string starting from the last forward slash.
You could use a function that explodes() the $path variable into an array and then array_pop to get rid of the last element.
function path($path) {
$arrayPath = explode("/", $path);
$path = array_pop($arrayPath);
return $path = implode("/", $path);
}
The shortest variant in PHP is:
$path = preg_replace('|/[^/]*$|','', $path);
which uses a regular expression.

Categories