PHP replace space with - expect at the end - php

I have this code here:
$this->view->category_name = $categoryName;
$albumName = strtolower($categoryName);
$albumName = preg_replace('/[\s-]+/', '-', $albumName);
and what this does it turn my string into lowercase and replace spaces with - ...however I have a category named "Miscellaneous" my code above turns into "miscellaneous" and then "miscellaneous-" how come its doing this and how can I adjust my code so it does not add it to the end?

Just remove the last dash. Finish off your code with:
$albumName = trim($albumName, '-');

Related

codeigniter: trying to remove "&" sign from image name, but not happening, bcoz of that getimagesize() giving error

codeigniter: trying to remove "&" sign from image name, but not happening, bcoz of that getimagesize() giving error
I am working on image uploading, but getting issue when image contains "&" symbol in image name.
I am trying to remove that symbole from image name but not happening.
Tried With Following Statements:
$filename = str_replace(" ","&",$_FILES["prod_images"]["name"][$i]);
$filename = str_replace(" ","&",$_FILES["prod_images"]["name"][$i]);
$filename = str_replace(" ","&",$_FILES["prod_images"]["name"][$i]);
But "&" symbol is not getting removed from image name.
please suggest me changes or statement.
You can use:
$filename = preg_replace("/[&_' ]/","",$_FILES["prod_images"]["name"][$i]);
put all unwanted characters in square brackets
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}
then
$filename = clean($_FILES["prod_images"]["name"][$i]);

Remove Path from PHP String front and back

i have bellow string in php and i want remove directory listing and get only the xml name
/usr/local/EDI/GTNexus/BookingConfirmation/test/PROCESSED/ELITESGGTN_30120180814_1410366355.XML_20180817135443
i want to return the string as ELITESGGTN_30120180814_1410366355.XML.
i use below way but im not getting the expected result
to remove front i used this but not getting the expected outcome
$newfname = strstr($fname, '/');
You can explode on "/" and then find the last undescore from the last item and substring it.
$str = "/usr/local/EDI/GTNexus/BookingConfirmation/test/PROCESSED/ELITESGGTN_30120180814_1410366355.XML_20180817135443";
$arr = explode("/", $str);
$name = substr(end($arr), 0, strrpos(end($arr), "_"));
echo $name; //ELITESGGTN_30120180814_1410366355.XML

remove line where multiple characters are present

I am reading file with file_get_contents.
Some lines can have multiple "=" chars and I want to remove these lines.
I tried
str_replace("=", "", $content);
but this replaces all occurences of "=" but not removes these lines.
Any idea please?
UPDATE: my content from file looks like this:
something
apple is =greee= maybe red
sugar is white
sky is =blue
Without seeing an example of your file/strings, it's a bit tricky to advise, but the basic principle I would work to would be something like this:
$FileName = "PathToFile";
$FileData = file_get_contents($FileName);
$FileDataLines = explode("\r\n", $FileData); // explode lines by ("\n", "\r\n", etc)
$FindChar = "="; // the character you want to find
foreach($FileDataLines as $FileDataLine){
$NoOfChar = substr_count($FileDataLine, $FindChar); // finds the number of occurrences of character in string
if($NoOfChar <= 1){ // if the character appears less than two times
$Results[] = $FileDataLine; // add to the results
}
}
# print the results
print_r($Results);
# build a new file
$NewFileName = "YourNewFile";
$NewFileData = implode("\r\n", $Results);
file_put_contents($NewFileName, $NewFileData);
Hope it helps

Looking to finish my url encoding in php

I have a slug function that I am using from another tutorial.
public function createSlug($slug) {
// Remove anything but letters, numbers, spaces, hypens
// Remove spaces and duplicate dypens
// Trim the left and right, removing any left over hypens
$lettersNumbersSpacesHypens = '/[^\-\s\pN\pL]+/u';
$spacesDuplicateHypens = '/[\-\s]+/';
$slug = preg_replace($lettersNumbersSpacesHypens, '', mb_strtolower($slug, 'UTF-8'));
$slug = preg_replace($spacesDuplicateHypens, '-', $slug);
$slug = trim($slug, '-');
return $slug;
}
It works great. I have two questions.
It gives me 'amp' instead of removing the '&' symbol. Not sure if it should be like that.
For eg.
original url
http://www.mywebsite.com?category_id=1&category_name=hot & dogs
new url using slug function
http://www.mywebsite.com?category_id=1&category_name=hot-amp-dogs
and second, how do I decode it back to the original form so that I can echo it out on the page? It doesn't look right echoing with dashes.
Use "htmlspecialchars_decode". see below modified function:
function createSlug($slug) {
// Remove anything but letters, numbers, spaces, hypens
// Remove spaces and duplicate dypens
// Trim the left and right, removing any left over hypens
$slug = htmlspecialchars_decode($slug);
$lettersNumbersSpacesHypens = '/[^\-\s\pN\pL]+/u';
$spacesDuplicateHypens = '/[\-\s]+/';
$slug = preg_replace($lettersNumbersSpacesHypens, '', mb_strtolower($slug, 'UTF-8'));
$slug = preg_replace($spacesDuplicateHypens, '-', $slug);
$slug = trim($slug, '-');
return $slug;
}
For decode, agree with Rakesh Sharma. Use database to manage this.

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.

Categories