I am trying to get the percentage value of download from the following string.
[download] Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.mp4
[download] 100% of 1.60MiB in 00:21
[download] Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.m4a
[download] 100% of 164.86KiB in 00:01
For ex. only the value '100' between '[download]' and '% of'.
This is my code what I've tried so far
$file = file_get_contents("t.txt");
if (preg_match_all("/(?<=\[download\])(.*?)(?=\% of)/s", $file, $result))
for ($i = 1; count($result) > $i; $i++) {
print_r($result[$i]);
}
But the problem is it grabs from the first line and outputs like
Array ( [0] => Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.mp4 [download] 100 [1] => Destination: Kool - Get Noticed - Apurbo-7CggL03TTl4.m4a [download] 100 )
If I can grab just before the '% of' that will be okay I think. Should I stick to this code for modifying or change the whole pattern?
This should work for you:
Here I first get your file into an array with file() where every line is one array element. There I ignore new line characters and empty lines.
After this I go through each line with array_map() where I check with preg_match_all() if there is a pattern like this: [download] (\d+)% of. If it finds the number I return it otherwise I return false and at the end I filter the elements with false with array_filter() out.
<?php
$lines = file("t.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$numbers = array_filter(array_map(function($v){
if(preg_match_all("/\[download\] (\d+)% of/", $v, $m))
return $m[1][0];
else
return false;
}, $lines));
print_r($numbers);
?>
output:
Array ( [1] => 100 [3] => 100 )
Related
Hello I have a text which written like this:
sh222022 HALIMA 20220329 1200 -21.4 82.5 S TS 45 994
wp932022 INVEST 20220329 1200 11.1 115.7 W DB 20 1008
I try separate word each but it didnt work
<?php
// get files content
$file_investraw = file_get_contents("./cache/data.txt", FILE_IGNORE_NEW_LINES);
// put the data into arrays
$data_investraw = explode("\n", $file_investraw);
?>
I want the output like this, so how should I echo each word I like?:
sh222022
HALIMA
20220329
1200
-21.4
82.5
S
TS
45
994
or if I want to echo each word or each value, I cant separate it. Thank You
you can do that like this.
// get files content
$file_investraw = file_get_contents("./cache/data.txt", FILE_IGNORE_NEW_LINES);
// put the data into arrays and remove the empty element from array
$data_investraw = array_filter(explode("\n", $file_data));
// make the array filter data into string
$data_investraw = implode(' ',$data_investraw);
// explode the string into array
$data_investraw = array_filter(explode(" ", $data_investraw));
this way you can achieve your desired output.
I have an htm file that holds scores for a game. I need to find each score above a 65, insert those scores and names only into a db and then print the entire file on the page with the high score lines in red. The htm file includes simple text:
<pre>
Thursday Afternoon Pairs Thursday Aft Session February 1, 2018
Scores after 5 rounds Average: 50.0 Section A North-South
Pair Pct Score Section Rank MPs
A B C
5 65.00 65.00 A 1 0.50(A) Joseph - Marlene
1 47.00 47.00 B 2/3 1 0.30(A) Janet - Mina
3 47.00 47.00 A 2/3 0.30(A) Renee - Reichle
</pre>
There is no other tags in the file and the file cannot be modified.
I've only gotten as far as trying to find the highscores and see if I can get those to print. This returns no matches found everytime.
$file = 108911.htm;
$pct = "([1-9][0-9]\.[0-9]{2})";
$highgame_pct = 65;
$contents = file_get_contents($file);
$pattern = preg_quote($pct, '/');
$pattern = "/^.*$pct.*\$/m";
if(preg_match_all($pattern, $contents, $matches) >= $highgame_pct){
echo "Found matches:<br />";
echo implode("<br />\n", $matches[0]);
}
else{
echo "No matches found";
}
preg_match_all returns the number of full pattern matches (which might be zero), or FALSE if an error occurred.
Using similar regex pattern and using callback function to filter array:
# define array filter callback function
function filterArray($value1){
return ($value1 >= 65.00);
}
# read file
$file = "108911.htm";
$contents = file_get_contents($file);
# define regex
$pattern = "/(\d{2}\.\d{2})/m";
# find matches
$val = preg_match_all($pattern, $contents, $matches);
echo "Count of matches = $val\n";
# filter matches array
$filteredArray = array_filter($matches[0], 'filterArray');
# print matched element
if (count($filteredArray) > 0) {
echo "Found matches bigger or equal to 65.00:<br />";
echo implode("<br />\n", $filteredArray);
}
else{
echo "No matches found";
}
Output:
Count of matches = 10
Found matches bigger or equal to 65.00:<br />
65.00<br />
65.00
You still need to modify this to match the "Score" column only.
Like anything, there are a lots of ways to do this, here is one to try:
# Set the threshold
$max = 65;
# This will fetch file to array, trim spaces, then remove empty
# using file() will take the file and automatically turn it to an array
$arr = array_filter(file('108911.htm',FILE_SKIP_EMPTY_LINES),function($v){
return (!empty(trim($v)));
});
# This will iterate and find matched values based on pattern
$file = array_values(array_filter(array_map(function($v) use ($max){
# Find values that match decimal pattern (allows 1 to 3 whole numbers and up to 2 decimal points)
preg_match_all('/[0-9]{1,3}\.[0-9]{1,2}/',$v,$match);
# Checks if there are at least 3 values in matched array
$match = (!empty($match[0]) && count($match[0]) == 3)? $match[0] : false;
# If not, just return empty
if(empty($match))
return false;
# If the second value (Points) is less than the max, return empty
if($match[1] < $max)
return false;
# Get the name value
preg_match('/[\w]+ - [\w]+/',$v,$name);
# Return the points and the name
return [
'points' => $match[1],
'name' => $name[0]
];
},$arr)));
# Here is the raw array. You can loop this now to get the rows to insert
print_r($file);
Gives you:
Array
(
[0] => Array
(
[points] => 65.00
[name] => Joseph - Marlene
)
)
do {
if ($dir[$i] == " " || is_numeric($dir[$i])
{
$direccion=$direccion.$dir[$i];
}
elseif ($i>6)
{
$i=strlen($dir)
}
}
while ($i <= count($dir))
$dir is the variable i use to get a google address, but the thing is that it comes with Zip code and City. The thing is that I only need the Street and number.
in the first run $dir = "Calle 30 433B29938 LaPlataBuenosAiresArgentina"
And i only need from that 30 433
Since the word " Calle " is always in the return, I've made an if that if its > 6, $i automatically will equal the lenght of the chain and kick me out of the while, because I'll be in "Calle " and there's when the 30 433 begins. The other ifs that I've made, one of them controls if It's a space to add it to the new string $direccion, and the other one checks if It's a number. If it's not a number and if It's not a space and $i > 6, means that I'm in B and I want to finish the do/while.
result of $direccion should be = 30 433. But i get an error on line 3 telling me that there is a problem with a {.
first thing you forget a ) at the end of your if condition
if ($dir[$i] == " " || is_numeric($dir[$i]))
and second if you want to get number out of a string you can use
preg_match_all('!\d+!', $str, $matches);
like if i use this code
$str = 'Calle 30 433B29938 LaPlataBuenosAiresArgentina ';
preg_match_all('!\d+!', $str, $matches);
output will be
Array ( [0] => Array ( [0] => 30 [1] => 433 [2] => 29938 ) )
But only if you are sure that your string will be exact you defined.
i am not sure but hope it can help.
I have created a function which randomly generates a phrase from a hardcoded list of words. I have a function get_words() which has a string of hardcoded words, which it turns into an array then shuffles and returns.
get_words() is called by generate_random_phrase(), which iterates through get_words() n times, and on every iteration concatenates the n word into the final phrase which is destined to be returned to the user.
My problem is, for some reason PHP keeps giving me inconsistent results. It does give me words which are randomized, but it gives inconsistent number of words. I specify 4 words as the default and it gives me phrases ranging from 1-4 words instead of 4. This program is so simple it is almost unbelievable I can't pinpoint the exact issue. It seems like the broken link in the chain is the $words array which is being indexed, it seems like for some reason sometimes the indexing fails. I am unfamiliar with PHP, can someone explain this to me?
<?php
function generate_random_phrase() {
$words = get_words();
$number_of_words = get_word_count();
$phrase = "";
$symbols = "!##$%^&*()";
echo print_r($phrase);
for ($i = 0;$i < $number_of_words;$i++) {
$phrase .= " ".$words[$i];
}
if (isset($_POST['include_numbers']))
$phrase = $phrase.rand(0, 9);
if (isset($_POST['include_symbols']))
$phrase = $phrase.$symbols[rand(0, 9)];
return $phrase;
}
function get_word_count() {
if ($_POST['word_count'] < 1 || $_POST['word_count'] > 9)
$word_count = 4; #default
else
$word_count = $_POST['word_count'];
return $word_count;
}
function get_words() {
$BASE_WORDS = "my sentence really hope you
like narwhales bacon at midnight but only
ferver where can paper laptops spoon door knobs
head phones watches barbeque not say";
$words = explode(' ', $BASE_WORDS);
shuffle($words);
return $words;
}
?>
In $BASE_WORDS your tabs and new lines are occupying a space in the exploded array that's why. Remove the newlines and tabs and it'll generate the correct answer. Ie:
$BASE_WORDS = "my sentence really hope you like narwhales bacon at midnight but only ferver where can paper laptops spoon door knobs head phones watches barbeque not say";
Your function seems a bit inconsistent since you also include spaces inside the array, thats why when you included them, you include them in your loop, which seems to be 5 words (4 real words with one space index) is not really correct. You could just filter spaces also first, including whitespaces.
Here is the visual representation of what I mean:
Array
(
[0] => // hello im a whitespace, i should not be in here since im not really a word
[1] => but
[2] =>
[3] => bacon
[4] => spoon
[5] => head
[6] => barbeque
[7] =>
[8] =>
[9] => sentence
[10] => door
[11] => you
[12] =>
[13] => watches
[14] => really
[15] => midnight
[16] =>
So when you loop it, you include spaces, in this case. If you got a number of words of 5, you really dont get those 5 words, index 0 - 4 it will look like you only got 3 (1 => but, 3 => bacon, 4 => spoon).
Here is a modified version:
function generate_random_phrase() {
$words = get_words();
$number_of_words = get_word_count();
$phrase = "";
$symbols = "!##$%^&*()";
$words = array_filter(array_map('trim', $words)); // filter empty words
$phrase = implode(' ', array_slice($words, 0, $number_of_words)); // no need for a loop
// this simply gets the array from the first until the desired number of words (0,5 or 0,9 whatever)
// and then implode, just glues all the words with space
// so this ensure its always according to how many words you want
if (isset($_POST['include_numbers']))
$phrase = $phrase.rand(0, 9);
if (isset($_POST['include_symbols']))
$phrase = $phrase.$symbols[rand(0, 9)];
return $phrase;
}
Inconsistent spacing in your words list is the issue.
Here is a fix:
function get_words() {
$BASE_WORDS = "my|sentence|really|hope|you|
|like|narwhales|bacon|at|midnight|but|only|
|ferver|where|can|paper|laptops|spoon|door|knobs|
|head|phones|watches|barbeque|not|say";
$words = explode('|', $BASE_WORDS);
shuffle($words);
return $words;
}
I want to format the credit cards like below when i display it,
Eg:
1234 4567 9874 1222
as
1xxx xxxx xxx 1222
Is there any formatting function like this in Yii ?
No - but there's nothing wrong with using straight PHP.
If you always want the 1st and the last 4 chars you can do something like this:
$last4 = substr($cardNum, -4);
$first = substr($cardNum, 0, 1);
$output = $first.'xxx xxxx xxxx '.$last4;
There are many ways to do this, nothing Yii specific
You could do it using str_split (untested):
$string = "1234 4567 1234 456";
$character_array = str_split($string);
for ($i = 1; $i < count($character_array) - 4; $i++) {
if ($character_array[$i] != " "){
$character_array[$i] = "x";
}
}
echo implode($character_array);
So we are creating an array of characters from the string called
$character_array.
We are then looping thru the characters (starting from position 1,
not 0, so the first character is visible).
We loop until the number of entries in the array minus 4 (so the last
4 characters are not replaced) We replace each character in the loop
with an 'x' (if it's not equal to a space)
We the implode the array back into a string
And you could also use preg_replace :
$card='1234 4567 9874 1222';
$xcard = preg_replace('/^([0-9])([- 0-9]+)([0-9]{4})$/', '${1}xxx xxxx xxxx ${3}', $card);
This regex will also take care of hyphens.
There is no in-built function in Yii.