PHP -- replace text in an array constructed from file php function - php

I have string and I would like to remove words which are part of the string and in the array. The array was created using the file function and the preg_replace function to delete patterns from the array occurring within a sentence.
Although, I am not getting errors, the replace is not working. I would really appreciate any help, I have been trying to get it to work these last 3 days but I haven't managed to do so :( and it is driving me crazy.
This is what I have done so far:
PHP code:
$test=file('files/stop_words.txt');
echo $test;
$no_stop=str_replace('|$test|', 'lllll', $sentence);
echo "<br>" .$no_stop;
Stop_words.txt file excerpt:
|alone|
|along|
|alongside|
|already|
|also|
|although|
|always|
|am|
|amid|
|amidst|
|among|
|amongst|
|an|
Thanks

I am adding a sample sentence so you can see it working.
I swapped out file with file_get_contents so that you could remove the | on each side before doing the check.
str_replace can accept an array, but it must be setup for exact matches, so having "|among|" instead of just "among" would hinder as well.
$sentence = "I stood alone in the yard";
$test = file_get_contents('files/stop_words.txt'); // Load in as a string
$test = str_replace("|", "", $test); // Remove unneeded |
$testList = explode("\n", $test); // Turn into an array
$filtered_sentence = str_replace($testList, 'lllll', $sentence); // Pass array into str_replace
echo $filtered_sentence;

Related

How to make a list to keyword list with PHP

I want to do something with PHP .
I have this list of names :
first
second
third
forth
Now i want to have this :
first,second,third,forth
How can this happen with a little PHP code ?
Assuming that you have those in array
$arr=array('first','second');
$str=implode(",",$arr);
EDIT(assuming each names are on the new line, i will replace \n with ,)
$str=file_get_contents("filename.txt");
$newstr=str_replace("\n",',',$str);
$newstr=trim($newstr, ",");//to remove the last comma
echo $newstr;
i think you text tag based on new line, so try this
first
second
third
forth
$arr = explode("\n", $txt);
echo implode(",",$arr);
every new line consider as a array value.
This is really basic PHP, I can't believe it isn't covered in most tutorials.
$array = file("filename", FILE_IGNORE_NEW_LINES);
$string = implode(',', $array);
I think you're looking for explode, like so http://us2.php.net/explode
array explode ( string $delimiter , string $string [, int $limit ] )
You want to set $delimiter to ' ', $string can be a copy -> paste of your text.txt content.
The best thing to do would be: take the text.txt content and use search-replace to remove new lines and add spaces (or commas), so you go from
ron
john
kahn
to ron, john, kahn, at which point you can import an array for use in php.

Counting Variables using PHP

Building a simple jQuery/PHP setup where for example the PHP will store 5 variables each containing a simple string. These variables are all separate and not in an array. The jQuery used is just a simple fadeIn/fadeOut function which fades out the 1st string and fades in the 2nd string. Got all that working.
However this is for a client who doesn't really even know what a variable is and has asked that the 5 strings be "changable" so I'm creating a seperate PHP file that contains the strings so that the client can just open that file and change the strings within there and possibly add/delete strings from the file.
What I want the php to do is "count" how many variables there are then echo each string depending on how many variables there are. Variables are named like so
$text_0 = "Its a sentence";
$text_1 = "Its another sentence";
$text_2 = "Its a final sentence";
so obviously need a for statement
for(i=0;i<WHATGOESHERE?;i++){
echo $text_[i];
}
Thanks for any help.
If you want it to be editable for a non techguy, then dont even use the variables as its to easy to forget a ; or a $ or whatever. Just create a plain text file and in PHP use it as an array.
An added bonus is that the none tech guy is not able to inject PHP code to your system.
file.txt:
Its a sentence
Its another sentence
Its a final sentence
show.php:
<?php
$lines = file('file.txt');
//below is just an example, obviously it should be your jquery code
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
//length would be count($lines) and upper bound count($lines)-1
?>
Give this to your non-techie:
Its a sentence
Its another sentence
Its a final sentence
Convert it into an array with:
$sentences = file('sentences.txt', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
Done.
<?php
$text_0 = 'a';
$text_1 = 'b';
$text_2 = 'c';
$vars = preg_grep('#^text_\d+$#', array_keys(get_defined_vars()));
var_dump($vars);
?>
It's better to create array $text..

parsing inline variables from string from file in php

I'm localizing a website that I've built. I'm doing this by having a .lang file read and each line (syntax: key=string) is placed in a variable depending on the chosen language.
This array is then used to place the strings in the correct places.
The problem I'm having is that certain strings need to have hyperlinks in the middle of them for example someplace I've put my name that links to my contact page. Or a lot of the readouts of the website need to be in the strings.
To solve this I've defined a variable that holds the html + Forecaster + html,
and the localization file contains the $Forecaster variable in the string.
The problem with this as I promptly discovered is that it stubbornly refuses to parse the inline variables in the strings from the file.
Instead it prints the string and variable name as it looks in the file.
And I have yet to find a way to make it parse the variables.
For example "Heating up took $str_time" would be printed on the page exactly like that, instead of inputting the previously defined value of $str_time.
I currently use fopen() and fgets() to open and read the lines. I then explode them to separate the key and the string and then place these into the array.
Is there a way to make it parse the variables, or alternatively is there another way of reading the lines that allows for parsing the inline variables?
The code that gets the line and converts it to the array looks like this:
(It obviously loops through the lines)
#list($key, $string) = explode('=', $line);
$key = strtok($line, '=');
$string = strtok('=');
$local[$key] = $string;
$counter++;
echo $local[$key] . "<br>";
The counter is unused and the echo is for testing.
A line from the .lang file looks like this:
fuel.results.heatup.timeused=Heating up took $str_time
I would call the array where I want the string like this:
$local['fuel.results.heatup.timeused']
As you can see I've tried both explode and strtok but it hasn't made a difference.
Personally I'd write your text file in JSON format to make it easier to pull data out.
Here is a solution directly from the php manual: http://nz2.php.net/manual/en/function.eval.php
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
It is worth noting that eval() can be very dangerous used in the wrong way so make sure you're code is very secure E.g. if someone altered your txt file with real PHP code they could execute it directly on the server.
Another approach would require you to know all your variable names and could then do something like:
$str = 'Heating up took $str_time';
echo 'str=' . str_replace('$str_time', $str_time, $str);
Or do this via an array:
$str = 'Heating up took $str_time as well as $other_value';
$vars = Array('str_time', 'other_value');
foreach($vars as $varName) {
$str = str_replace('$' . $varName, $$varName, $str);
}
echo 'str=' . $str;
If you not know all the variable name, you can use this example, without eval(). It is indicatred to avoid eval().
$str = 'fuel.results.heatup.timeused=Heating up took $str_time';
$str_time = 'value';
if(preg_match('/\$([a-z0-9_]+)/i', $str, $v)) {
$vname = $v[1];
$str = str_replace('$'.$vname, $$vname, $str);
}
echo $str; // fuel.results.heatup.timeused=Heating up took value

How to search for a pattern like [num:0] and replace it?

I know there are lots of tutorials and question on replacing something in a string.
But I can't find a single one on what I want to do!
Lets say I have a string like this
$string="Hi! [num:0]";
And an example array like this
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
Now what I want is that PHP should first search for the pattern like [num:x] where x is a valid key from the array.
And then replace it with the matching key of the array. For example, the string given above should become: Hi! na
I was thinking of doing this way:
Search for the pattern.
If found, call a function which checks if the number is valid or not.
If valid, returns the name from the array of that key like 0 or 1 etc.
PHP replaces the value returned from the function in the string in place of the pattern.
But I can't find a way to execute the idea. How do I match that pattern and call the function for every match?
This is just the way that I am thinking to do. Any other method will also work.
If you have any doubts about my question, please ask in comments.
Try this
$string="Hi! [num:0]";
$array=array();
$array[0]=array('name'=>"na");
$array[1]=array('name'=>"nam");
echo preg_replace('#(\!)?\s+\[num:(\d+)\]#ie','isset($array[\2]) ? "\1 ".$array[\2]["name"] : " "',$string);
If you don't want the overhead of Regex, and your string format remains same; you could use:
<?php
$string="Hi! [num:0]";
echo_name($string); // Hi John
echo "<br />";
$string="Hello! [num:10]";
echo_name($string); // No names, only Hello
// Will echo Hi + Name
function echo_name($string){
$array=array();
$array[0]=array('name'=>"John");
$array[1]=array('name'=>"Doe");
$string = explode(" ", $string);
$string[1] = str_replace("[num:", "", $string[1]);
$string[1] = str_replace("]", "", $string[1]);
if(array_key_exists($string[1], $array)){
echo $string[0]." ".$array[$string[1]]["name"];
} else {
echo $string[0]." ";
}
}// function echo_sal ENDs
?>
Live: http://codepad.viper-7.com/qy2uwW
Assumptions:
$string always will have only one space, exactly before [num:X].
[num:X] is always in the same format.
Of course you could skip the str_replace lines if you could make your input to simple
Hi! 0 or Hello! 10

php simplest case regex replacement, but backtraces not working

Hacking up what I thought was the second simplest type of regex (extract a matching string from some strings, and use it) in php, but regex grouping seems to be tripping me up.
Objective
take a ls of files, output the commands to format/copy the files to have the correct naming format.
Resize copies of the files to create thumbnails. (not even dealing with that step yet)
Failure
My code fails at the regex step, because although I just want to filter out everything except a single regex group, when I get the results, it's always returning the group that I want -and- the group before it, even though I in no way requested the first backtrace group.
Here is a fully functioning, runnable version of the code on the online ide:
http://ideone.com/2RiqN
And here is the code (with a cut down initial dataset, although I don't expect that to matter at all):
<?php
// Long list of image names.
$file_data = <<<HEREDOC
07184_A.jpg
Adrian-Chelsea-C08752_A.jpg
Air-Adams-Cap-Toe-Oxford-C09167_A.jpg
Air-Adams-Split-Toe-Oxford-C09161_A.jpg
Air-Adams-Venetian-C09165_A.jpg
Air-Aiden-Casual-Camp-Moc-C09347_A.jpg
C05820_A.jpg
C06588_A.jpg
Air-Aiden-Classic-Bit-C09007_A.jpg
Work-Moc-Toe-Boot-C09095_A.jpg
HEREDOC;
if($file_data){
$files = preg_split("/[\s,]+/", $file_data);
// Split up the files based on the newlines.
}
$rename_candidates = array();
$i = 0;
foreach($files as $file){
$string = $file;
$pattern = '#(\w)(\d+)_A\.jpg$#i';
// Use the second regex group for the results.
$replacement = '$2';
// This should return only group 2 (any number of digits), but instead group 1 is somehow always in there.
$new_file_part = preg_replace($pattern, $replacement, $string);
// Example good end result: <img src="images/ch/ch-07184fs.jpg" width="350" border="0">
// Save the rename results for further processing later.
$rename_candidates[$i]=array('file'=>$file, 'new_file'=>$new_file_part);
// Rename the images into a standard format.
echo "cp ".$file." ./ch/ch-".$new_file_part."fs.jpg;";
// Echo out some commands for later.
echo "<br>";
$i++;
if($i>10){break;} // Just deal with the first 10 for now.
}
?>
Intended result for the regex: 788750
Intended result for the code output (multiple lines of): cp air-something-something-C485850_A.jpg ./ch/ch-485850.jpg;
What's wrong with my regex? Suggestions for simpler matching code would be appreciated as well.
Just a guess:
$pattern = '#^.*?(\w)(\d+)_A\.jpg$#i';
This includes the whole filename in the match. Otherwise preg_replace() will really only substitute the end of each string - it only applies the $replacement expression on the part that was actually matched.
Scan Dir and Expode
You know what? A simpler way to do it in php is to use scandir and explode combo
$dir = scandir('/path/to/directory');
foreach($dir as $file)
{
$ext = pathinfo($file,PATHINFO_EXTENSION);
if($ext!='jpg') continue;
$a = explode('-',$file); //grab the end of the string after the -
$newfilename = end($a); //if there is no dash just take the whole string
$newlocation = './ch/ch-'.str_replace(array('C','_A'),'', basename($newfilename,'.jpg')).'fs.jpg';
echo "#copy($file, $newlocation)\n";
}
#and you are done :)
explode: basically a filename like blah-2.jpg is turned into a an array('blah','2.jpg); and then taking the end() of that gets the last element. It's the same almost as array_pop();
Working Example
Here's my ideaone code http://ideone.com/gLSxA

Categories