Add data to an array - php

I have manage to get the information I need from a website. Now I want to insert the data into an array, so I can easily insert the information to the database.
Here's how the code looks like right now:
<?php
$page = file_get_contents("http://www.kalender.se/helgdagar");
$string = trim(preg_replace('/\s\s+/', '', $page));
$string = preg_replace("#<a.*?>(.*?)<\/a>#s", '|\1', $string);
preg_match_all("/<td>([\d-]{10})<\/td><td>(.*?)<\/td>/s", $string, $matches);
foreach($matches[0] AS $test) {
$splitted = explode('|', $test);
echo '<pre>'; print_r($splitted[0]); echo '</pre>';
}
?>
Which prints out the following with $splitted[0]:
2018-01-01
2018-01-06
2018-03-30
2018-04-01
2018-04-02
2018-05-01
2018-05-10
2018-05-20
2018-06-06
2018-06-23
2018-11-03
2018-12-25
2018-12-26
And with $splitted[1]:
Nyårsdagen
Trettondedag jul
Långfredagen
Påskdagen
Annandag påsk
Första maj
Kristi himmelfärdsdag
Pingstdagen
Sveriges nationaldag
Midsommar
Alla helgons dag
Juldagen
Annandag jul
I want this information to be grouped and also be in an array, like this:
Array(
'2018-01-01' => 'Nyårsdagen',
'2018-01-06' => 'Trettondedag jul',
... and so on
);
How can I accomplish this?

I didn't even know that array_combine() even existed until Jon Stirling mentioned it in his comment. Many thanks, Jon! :)
Here's the final result:
<?php
$page = file_get_contents("http://www.kalender.se/helgdagar");
$string = trim(preg_replace('/\s\s+/', '', $page));
$string = preg_replace("#<a.*?>(.*?)<\/a>#s", '\1', $string);
preg_match_all("/<td>([\d-]{10})<\/td><td>(.*?)<\/td>/s", $string, $matches);
$array_test_1 = Array();
foreach($matches[1] AS $test1) {
$array_test_1[] = $test1;
# echo '<pre>'; print_r($splitted[1]); echo '</pre>';
}
$array_test_2 = Array();
foreach($matches[2] AS $test2) {
$array_test_2[] = $test2;
# echo '<pre>'; print_r($splitted[1]); echo '</pre>';
}
$finishit = array_combine($array_test_1, $array_test_2);
echo '<pre>'; print_r($finishit); echo '</pre>';
?>

Related

php remove duplicate except original

this is my code
<?php
$string = 'this
this
good
good
hahah';
$rows = explode("\n",$string);
$unwanted = 'this|good';
$cleanArray= preg_grep("/$unwanted/i",$rows,PREG_GREP_INVERT);
$cleanString=implode("\n",$cleanArray);
print_r ( $cleanString );
?>
display
hahah
i want like this
this
good
hahah
i want to keep one...
please help me, thanks guys
This code resorts to checking each line to see if it matches your $unwanted string, but it also creates an array of strings it has already encountered so it checks if it has previously been encountered ( using in_array()). If it matches and has been encountered before it uses unset() in the original $rows to remove the line...
$string = 'this
this
good
good
hahah';
$rows = explode("\n",$string);
$unwanted = 'this|good';
$matched = [];
foreach ( $rows as $line => $row ) {
if ( preg_match("/$unwanted/i",$row, $matches)) {
if ( in_array(trim($matches[0]), $matched) === true ) {
unset($rows[$line]);
}
$matched[] = $matches[0];
}
}
$cleanString=implode("\n",$rows);
print_r ( $cleanString );
<?php
$string = 'this
this
good
yyyy
good
xxxx
hahah';
print_r(
implode("\n",
array_diff(array_unique(
array_map(function($v) { return trim($v);}, explode("\n",$string))
)
,array('xxxx', 'yyyy')))
);
?>
output:
this
good
hahah
Refer: https://ideone.com/Eo0MIM
You can use this simple code to get result:
$result = array_unique(explode("\n",str_replace(" ", "", $string)));
print_r ($result);
If you want more control over your data, use this code
$rows = explode("\n", $string);
$words = [];
foreach($rows as $row) {
$row = trim($row);
$words[$row] = true;
}
foreach($words as $word => $tmp) {
echo $word . "\n";
}
Here is one way you could do this:
$string = 'this
this
good
good
hahah';
preg_match_all('/([a-z])+/', $string, $matches);
$string = implode("\n",array_unique($matches[0]));
echo $string;
You can use php inbuilt array_unique function
<?php
$string = 'this
this
good
good
haha';
$rows = explode("\n",$string);
$cleanArray = array_unique($rows);
$cleanString=implode("\n",$cleanArray);
print_r ( $cleanString );
//result is this good haha

check the same char in strg and remove and split from underscore in PHP?

Hello I have one string "22A_n22A" and i want to remove the same character from this string and want to split from "_" to two string like 22A and n22A.
i tried it but did not get any solution.
final out put i want like 22A_n22A to (n)22AA
<?php
function conti($str,$case_sensitive = false) {
//if($com1 = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $newval))
if(strcmp($case_sensitive , $case_sensitive) === 0 )
{
$pieces = explode("_", $str);
$str1 = $pieces[0];
$str2 = $pieces[1];
$ary1 = str_split($str1);
$ary2 = str_split($str2);
if (isset($case_sensitive))
{
$ary1 = array_map('strtolower',$ary1);
$ary2 = array_map('strtolower',$ary2);
}
$com = implode('',array_intersect($ary1,$ary2));
$diff = implode('',array_merge(array_diff($ary1, $ary2),array_diff($ary2, $ary1)));
$int = (int) filter_var($com, FILTER_SANITIZE_NUMBER_INT);
$onlystr = preg_replace('/\d/', '', $com);
$newval= '('.$diff.')'.$int.$onlystr.$onlystr;
// $com1 = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $str);
echo '<pre><h1>';
echo 'new value:';
print_r($newval);
echo "<br>";
echo "<br>";
echo "<br>";
echo 'new value:';
print_r($com);
echo "<br>";
echo 'new diff:';
print_r($diff);
echo '</pre>';
return $newval;
}
else {
echo '<pre><h1>';
echo 'oldvalue:';
print_r($str);
echo '</pre>';
return $str;
}
}
echo(conti('71A_n71A'));
// echo(conti('66A_n66A'));
?>
As stated in your comments your requirement is to:
Split the string on _
Pluck the last character from the first chunk of the string and append that to the end of the second string
Wrap the first character of the second chunk of the string in parentheses
For example, 65A_n66A becomes (n)66AA.
You can do this with by performing explode() on the original string, extracting the parts you need and piecing them back together in your desired format:
function format($string) {
list($first, $second) = explode('_', $string);
return sprintf('(%s)%s%s',
$second[0],
substr($second, 1),
$first[strlen($first) - 1]
);
}
This yields:
echo format('22A_n22A'); // (n)22AA
echo format('11A_n22B'); // (n)22BA
echo format('65A_n66A'); // (n)66AA
Hope this helps :)

php: find any combination of 2 or 3 numbers in string and separate as variable

How can I find if a combination of 2 or 3 numbers exists in string and then split it in two variables?
example: $input = "this and that 12" or $input = "this and that 100"
I want to separate this strings into two variables:
$text = "this and that",
$number = "12" (or "100" as in the above example)
P.S string is user input and could as well not contain any number, example $input = "this and that";
Haven't tried but should work.
$number = preg_replace( '/[^0-9]/', '', $string );
$text = str_replace($number, "", $string);
Another one
$aStrings = array('This and that 123','This and Not That 12');
foreach($aStrings as $str){
preg_match('/\D+/',$str, $text);
preg_match('/\d+/', $str, $num);
echo "
$text[0]
$num[0]
- - - -
";
}
Output:
This and that
123
- - - -
This and Not That
12
- - - -
Example Code
Try this
<?php
$string1 = "this and that 12";
$string2 = "this and that 100";
$combine = explode(' ',$string1.' '.$string2);
$vars = '';
$integer ='';
foreach($combine as $key =>$val)
{
if(is_numeric($val))
{
$vars[] = $val;
}
else
{
$integer[] =$val;
}
}
echo "<pre>"; print_r(array_unique($vars));
echo "<pre>"; print_r(array_unique($integer));
?>
this will output
Array
(
[0] => 12
[1] => 100
)
Array
(
[0] => this
[1] => and
[2] => that
)
you try this code
$string="this and that 12";//this and that 100
preg_match_all('/^([^\d]+)(\d+)/', $string, $match);
echo $text = $match[1][0];
echo $num = $match[2][0];

How get filename from path php?

I have array with paths:
array (size=27692)
0 => string './users/58/576709/16376/16376.mp4'
(length=34)
1 => string './users/58/578974/45475/45475.mp4'
(length=34)
//...
How i can get for example 16376.mp4?
This should work for you:
<?php
$str = "./users/58/576709/16376/16376.mp4";
echo basename($str);
?>
Output:
16376.mp4
And if you have a Array, as an example:
<?php
$arr = array("./users/58/576709/16376/16376.mp4", "./users/58/578974/45475/45475.mp4");
foreach($arr as $v)
echo basename($v) . "<br />";
?>
Output:
16376.mp4
45475.mp4
Try this
$str = "./users/58/576709/16376/16376.mp4";
echo end(explode('/', $str));
$path = '/www/public_html/index.html';
$filename = substr(strrchr($path, "/"), 1);
Could also work so for array.
foreach($filepaths as $path){
$filename[] = substr(strrchr($path, "/"), 1);
}
This would give you a new array containing only the filename
This can be done using the following code:
$array = array(
0 => '/users/58/576709/16376/16376.mp4',
1 => '/users/58/576709/16376/16377.mp4'
);
echo $array[1];
$array = explode('/', $array[1]);
echo $array[sizeof($array) - 1];
Last line would print the filename

php get first and second word after (at)

I need some help with a php code which torment me 2-3 hours. Ny methods tried but no result. I want to take the first and second word after the #, eg #John Doe and php result took me John and Doe
I thing something that:
(Edited)
$q = 'Hi #Stefan Simeonov kak si? #Krasi avramov';
if (preg_match_all("(#[^ ]+[ ][^ ]+)", $q, $match)) {
foreach ($match[0] as $singleMatch) {
$finded[] = $singleMatch;
$success = 1;
}
} elseif (preg_match_all("(#[^ ]+)", $q, $match)) {
foreach ($match[0] as $singleMatch) {
$finded[] = $singleMatch;
$success = 1;
}
} else {
$success = 0;
}
if($success = 1) {
$replace = $q;
foreach ($finded as $user) {
$expl = explode("#",$user);
$rep = ''.$expl[1].'';
$replace = str_replace($user,$rep,$replace);
}
echo $replace;
} else {
echo $q;
}
Using a regular expression for example:
<?php
$q = 'Hi #John Doe kak si?';
if (preg_match('/#(\w+)\s(\w+)/', $q, $matches)) {
var_dump($matches);
}
This will look for a word after a #, followed by a space, followed by another word.
You can do something like this:
<?
$q = 'Hi #John Doe kak si?';
$explodeTab = explode("#",$q);
$words = explode(" ",$explodeTab[1]);
print_r($words);
?>
WORKING CODE
You can use a regex of (#[^ ]+[ ][^ ]+) for this:
<?php
$q = 'Hi #Stefan Simeonov kak si?';
if (preg_match_all("(#[^ ]+[ ][^ ]+)", $q, $match)) {
foreach ($match[0] as $singleMatch) {
echo 'Found match: ' . $singleMatch . PHP_EOL;
}
}
?>
Will output:
Found match: #Stefan Simeonov
Assuming that words are always separated by spaces, you can achieve this by first splitting the input string on the # character and then taking the 1th item and splitting that on the space character and reducing that result to the words that you need.
<?php
$q = 'Hi #John Doe kak si?';
$atSplitResult = explode('#', $q);
$spaceSplitResult = explode(' ', $atSplitResult[1]);
$firstTwoWords = array_slice($spaceSplitResult, 0, 2);
var_dump($firstTwoWords);
Let's say, we have a sentence
Let's see, #mike, how are you doing?
now:
$atExploded = explode('#', $str); //where $str is our string
if(count($atExploded)){
foreach($atExploded as $at){
$spaceExplode = explode(' ', $at);
echo $spaceExplode[0].' '.$spaceExplode[1]; //after checking that [0] and [1] are reachable
}
}
of course you should cut any unwanted characters (like braces, colons and so on) but I hope you get the idea.
PHP
$string = 'Hi #John Doe kak si?';
$regex = preg_match("/#(.+?)\s(.+?)\s/", $string, $matches);
var_dump($matches);
Returns
array(3) { [0]=> string(10) "#John Doe " [1]=> string(4) "John" [2]=> string(3) "Doe" }
You can write something like this. This will output #John Doe
<?php
$q = 'Hi #John Doe kak si?';
$q = preg_match('/#[A-Za-z]+\s[A-Za-z]+/', $q, $match);
print_r($match);
?>

Categories