How to dynamically update a file name with increasing integers? - php

I want to update a file name so that it looks like this each time it is updated.
some_name_1, some_name_2, some_name_3, etc.
Each update will increase the trailing integer by one. Below is my prototype, I wanted to make sure this is the best practice way to do it, before implementing it. Also, I'm not 100% PHP will do the implicit casting correctly.
Is this a good practice way to update a file name?
// ... in a class
private function updateFileName()
{
$pattern = '#_(\d+)$#';
$subject = $this->file_name; // $subject holds current file name
preg_match($pattern, $subject, $matches);
if($matches[0])
{
$patterns = array();
$temp = $matches[0];
$patterns[0] = '/$temp$/';
$replacements = array();
$replacements[0] = $matches[0] + 1;
preg_replace($patterns, $replacements, $subject); // $subject now holds new name
}
}
Clarification
The file name is actually a hash, and is one string of characters.
The _1, etc will always be at the end of the string ( perhaps good to use an anchor )

You can do the whole thing in one preg_replace:
preg_replace("/\b([^\w]+)\b/i",'_',$filename);

Related

find position of word in array php

I've nearly figured out my sms issue, and have it narrowed down to one small issue that I can't seem to get to work.
Here's what I have:
include('Services/Twilio.php');
/* Read the contents of the 'Body' field of the Request. */
$body = $_REQUEST['Body'];
/* Remove formatting from $body until it is just lowercase
characters without punctuation or spaces. */
$result = rtrim($body);
$result = strtolower($result);
$text = explode(' ',$result);
$keyword = array('dog','pigeon','owl');
$word = array_intersect($keyword,$text);
$key = array_search($word, array_keys($keyword));
$word[$key]();
/* ^^this is the issue */
So the SMS app now can read a sentence and find the keyword no sweat. Problem is, I also need to have the position of the word in relation to where it is in the keyword array. If I manually change the number to the correct position and send a text containing that keyword it functions flawlessly.
Unfortunately array_search doesn't work because it can't accept a dynamic needle. Is there any way to have the array position auto populate based on what keyword is found? In my code above, you can see (hopefully) what I'm trying to do.
Solved issue. It can be done dynamically.
$body = $_REQUEST['Body'];
/* Remove formatting from $body until it is just lowercase
characters without punctuation or spaces. */
$result = rtrim($body);
$result = strtolower($result);
$text = explode(' ',$result);
$keyword = array('listing','pigeon_show','owl');
$word = array_intersect($keyword,$text);
$key = key($word);
if ($word){
$word[$key]();}
else
{index();}

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 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.

Using preg_replace on words from file not working

Here is my source
$Message = $_GET["message"];
$Username = htmlspecialchars($_GET["username"]);
$unix = ($_GET["time"]);
include 'mcheck.php';
$file1 = file_get_contents('filter.txt');
$bad_words = explode(PHP_EOL, $file1);
$compare = explode('', $Message);
foreach ($bad_words as $bad_word)
$Message = preg_replace('/\b('.$bad_word.')\b/i', "***", $Message);
echo $Message;
Say the bad word is go
and $Message = I Like to go to school
I want it to echo I Like to *** to school
but instead im getting
***I***Like***To******to***school***
i dont know what the problem is
Based on the output, you likely have an empty element in your array. So it's ultimately matching a word boundary (\b).
To confirm this add the following to debug your code:
$bad_words = explode(PHP_EOL, $file1);
print_r($bad_words);
As an aside, it's a waste to loop over each bad word. I suggest using a single regex with alterations once you've resolved the above.
For example:
\b(one|two|three)\b
Why don't you just use str_replace
Example
$badWords = array("go","school");
$message = " I like to go to school" ;
$newMessage = str_replace($badWords, "***", $message);
echo $newMessage ;
Output
I like to *** to ***
Your file most likely ends with a newline (which is a good thing: all text-files on *nix systems are supposed to), which means that the last element of explode(PHP_EOL, $file1) is empty (it's everything between the last newline and the end of the file, which is nothing). I would recommend writing:
$file1 = trim(file_get_contents('filter.txt'));
using the trim function to eliminate that last newline.
i think yo need to remove empty fields from explode resulting array
You should use strtr for this purpose.
you can pass array with key=>replace, which will be somewhat more efficient that preg_replace
apart from that, must be bad badwords dic.

Can I use regex for this?

Is this possible with regex?
I have a file, and if a '#' is found in the file, the text after the '#' with the '#' is to be replaced with the file with the same name as after the '#'.
File1: "this text is found in file1"
File2: "this file will contain text from file1: #file1".
File2 after regex: "this file will contain text from file1: this text is found in file1".
I wish to do this with php and I've heard that the preg function is better than the ereg, but whatever works is fine with me =)
Thanks a lot!
EDIT:
It has to be programmed, so that it looks through file2 without knowing which files to concatenate before it has gone through all occurrences of a # :)
PHP's native functions str_pos and str_replace are better to use when you're searching through larger files or strings. ;)
First of all the grammar of your templating is not a very good one becuase the parser may not exactly sure when will the file name ends.
My suggestion would be that you change to the one that can better detect the boundry like {#:filename}.
Anyhow, the code I give below follows your question.
<?php
// RegEx Utility functions -------------------------------------------------------------------------
function ReplaceAll($RegEx, $Processor, $Text) {
// Make sure the processor can be called
if(!is_callable($Processor))
throw new Exception("\"$Processor\" is not a callable.");
// Do the Match
preg_match_all($RegEx, $Text, $Matches, PREG_OFFSET_CAPTURE + PREG_SET_ORDER);
// Do the replacment
$NewText = "";
$MatchCount = count($Matches);
$PrevOffset = 0;
for($i = 0; $i < $MatchCount; $i++) {
// Get each match and the full match information
$EachMatch = $Matches[$i];
$FullMatch = is_array($EachMatch) ? $EachMatch[0] : $EachMatch;
// Full match is each match if no grouping is used in the regex
// Full match is the first element of each match if grouping is used in the regex.
$MatchOffset = $FullMatch[1];
$MatchText = $FullMatch[0];
$MatchTextLength = strlen($MatchText);
$NextOffset = $MatchOffset + $MatchTextLength;
// Append the non-match and the replace of the match
$NewText .= substr($Text, $PrevOffset, $MatchOffset - $PrevOffset);
$NewText .= $Processor($EachMatch);
// The next prev-offset
$PrevOffset = $NextOffset;
}
// Append the rest of the text
$NewText .= substr($Text, $PrevOffset);
return $NewText;
}
function GetGroupMatchText($Match, $Index) {
if(!is_array($Match))
return $Match[0];
$Match = $Match[$Index];
return $Match[0];
}
// Replacing by file content -----------------------------------------------------------------------
$RegEx_FileNameInText = "/#([a-zA-Z0-9]+)/"; // Group #1 is the file name
$ReplaceFunction_ByFileName = "ReplaceByFileContent";
function ReplaceByFileContent($Match) {
$FileName = GetGroupMatchText($Match, 1); // Group # is the gile name
// $FileContent = get_file_content($FileName); // Get the content of the file
$FileContent = "{# content of: $FileName}"; // Dummy content for testing
return $FileContent; // Returns the replacement
}
// Main --------------------------------------------------------------------------------------------
$Text = " === #file1 ~ #file2 === ";
echo ReplaceAll($RegEx_FileNameInText, $ReplaceFunction_ByFileName, $Text);
This will returns === {# content of: file1} ~ {# content of: file2} ===.
The program will replace all the regex match with the replacement returned from the result of the given function name.
In this case, the callback function is ReplaceByFileContent in which the file name is extract from the group #1 in the regex.
I believe my code is self documented but if you have any question, you can ask me.
Hope I helps.
Much cleaner:
<?php
$content = file_get_content('content.txt');
$m = array();
preg_match_all('`#([^\s]*)(\s|\Z)`ism', $content, $m, PREG_SET_ORDER);
foreach($m as $match){
$innerContent = file_get_contents($match[1]);
$content = str_replace('#'.$match[1], $innerContent, $content);
}
// done!
?>
regex tested with: http://www.spaweditor.com/scripts/regex/index.php

Categories