PHP regex for image name with numbers - php

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.

Related

PHP match and replace whole word

Hi I am replacing certain names with different value . Here is values I am replacing "#size-name" and "#size" .But the problem is my code replacing only size first and note name for example
#size = "replaceword"
#size-name = "replaceword2"
But its replacing
#size ="replaceword"
#size-name = "replaceword2-name"
How can I replace whole word not part of it here is my code
$tempOutQuery = preg_replace("/(\b($key)\b)/i" , $value , $tempOutQuery);
$tempOutQuery= str_replace("#".$key ,$value ,$tempOutQuery);
both codes are not working
My Full Code
$val= "Hi I want #size dress which is #size-name";
$tempOutQuery = preg_replace("/(\b(size)\b)/i" ,"replaceword", $tempOutQuery);
$tempOutQuery = preg_replace("/(\b(size-name)\b)/i" ,"replaceword2", $tempOutQuery);
If you could make replace without using regulat expressions, then I would suggest using standart str_replace() with arrays:
$val= "Hi i want #size dress which is #size-name";
$search = array('size-name', 'size');
$replace = array('replaceword2', 'replaceword');
$result = str_replace($search, $replace, $val);
The order of search and replace Strings is important!
You should take care that you replace long search-strings first, and the short strings later.
Here's another option for you, using preg_replace_callback. It's actually very similar to Gennadiy's method. The only real difference is that it's using the preg aspect of PHP (and it's a lot more work). But it's another way to skin the proverbial cat.
<?php
// SET OUR DEFAULT STRING
$string = 'Hi I want #size suit which is #size-name';
// LOOK FOR EITHER size-name OR size AND IF YOU FIND IT ...
// RUN THE FUNCTION 'replace_sizes'
$string = preg_replace_callback('~#(size-name|size)~', 'replace_sizes', $string);
// PRINT OUT OUR MODIFIED STRING
print $string;
// THIS IS THE FUNCTION THAT WILL BE RUN EVERY TIME A MATCH IS FOUND
// EITHER 'size' OR 'size-name' WILL BE STORED IN $m[1]
function replace_sizes($m) {
// SET UP AN ARRAY THAT HAS OUR POTENTIAL MATCHES AS KEYS
// AND THE TEXT WE WANT TO REPLACE WITH AS THE VALUE
$size_text_array = array('size-name' => 'replaceword2', 'size' => 'replaceword');
// RETURN WHATEVER THE VALUE IS BASED ON THE KEY
return $size_text_array[$m[1]];
}
This will print out:
Hi I want replaceword suit which is replaceword2
Here is a working demo:
http://ideone.com/njNTbB
You can try pre_replace() to replace whole word from an item of an array in PHP a shown below.
<?PHP
function removePrepositions($text){
$propositions=array('/\bfor\b/i','/\band\b/i');
if( count($propositions) > 0 ) {
foreach($propositions as $exceptionPhrase) {
$text = preg_replace($exceptionPhrase, '', trim($text));
}
$retval = trim($text);
}
return $retval;
}
?>
See the entire post here

PHP how do i cut substring after last slash?

Hi i want to know how can i get substring from string after last slash?
In short i want to get the file name from path.
for example i got string like this:
test-e2e4/test-e2e4/test-e2e4/6.png
and i want to get 6.png how can i do that ?
I got dir only and the file name can be all format, it can be also something else then file
Or test-e2e4/test-e2e4/test-e2e4/aaaaa and want to get aaaaa
Regex maybe? Or maybe you know some nice functions which will do it for me ?
In addition to other replies, there's actually a function in PHP to do this: basename. Example:
$string = 'test-e2e4/test-e2e4/test-e2e4/6.png';
$base = basename($string); // $base == '6.png';
$string = 'test-e2e4/test-e2e4/test-e2e4/aaaaa';
$base = basename($string); // $base == 'aaaaa'
$string = '6.png';
$base = basename($string); // $base == '6.png'
Full details here: http://php.net/basename
Do like this..
$yourstring = 'test-e2e4/test-e2e4/test-e2e4/6.png';
$val = array_pop(explode('/',$yourstring)); // 6.png
You can try explode and array_pop functions to work this out:
$str = 'test-e2e4/test-e2e4/test-e2e4/aaaaa.png';
$str = explode('/', $str);
$filename = array_pop($str);
echo $filename; //Output will be aaaaa.png
...Or you can use the following regex:
[^\/]*$
You don't need to use regex for this, you can use substr() to get a portion of the string, and strrpos() to specify which portion:
$full_path = "test-e2e4/test-e2e4/test-e2e4/6.png"
$file = substr( $full_path, strrpos( $full_path, "/" ) + 1 );
substr() returns a portion of the string, strrpos() tells it to start from the position of the last slash in the string, and the +1 excludes the slash from the return value.

How to divide string in php

How can I add divider ; in the following variable which contains string
I have string like this:
$filename = "a.jpg3c.pngyes.jpg";
I would like to have something like
a.jpg;3c.png;yes.jpg
This string is created when I select multiple files to upload.
Is regex only solution in here?
Regex is not the only solution! Perhaps you can use str_replace() instead of regex.
$filenames = "a.jpg3c.pngyes.jpg";
$img_extensions = array(".png", ".jpg", ".gif");
$semicolon_additions = array(".png;", ".jpg;", ".gif;");
$newfilenames = str_replace($img_extensions, $semicolon_additions, $filenames);
http://php.net/manual/en/function.str-replace.php
Edit: In your particular case, I would add in the semicolon at the end of the filename inside of your loop.
Here is one option using regular expressions:
$filename = "a.jpg3c.pngyes.jpg";
$regex = '/\.(jpg|png|gif)(?!$)/';
$filename = preg_replace($regex, ".$1;", $filename);

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

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