One explode function for two date formats - php

I have two PHP variable $consult_date_arr and $consultationdate.the user can insert any date format consider for now 22-12-2014 or 22/12/2014.what i want to do is i want to write a explode function which should work for both the condition i.e. for both the date formats.
$consult_date_arr=explode("/",$consultationdate);
$consult_date_arr=explode("-",$consultationdate);
The explode function should be the combination of above two explode function in functionality,such date it works for both the formats.if any doubt please let me know.
thanks in advance.

try something like this
<?php
$date = '22/12/2014';
$keywords = preg_split("/[-,\/]+/", $date);
print_r($keywords);
?>
preg_split — Split string by a regular expression
REFERENCE
http://php.net/manual/en/function.preg-split.php

<?php
$dt = "1992-05-30";
//$dt = "1992/05/30";
function expld($date){
$date = str_replace("/", "-", $date);
$date = explode("-",$date);
return $date;
}
$newdate = expld($dt);
echo $newdate[0];
?>

you can write custom function and call explode inside it
like
$string = "-" OR "/" Or whatever you want to explode with
function dateFormat($string,$date)
{
$consult_date_arr=explode($string,$consultationdate);
return $consult_date_arr;
}

you will need regular expression, using preg_match in php.
<?php
$consult_date_arr;
$consultationdate = '22/12/2014';
if(preg_match('/[\d]{2}-[\d]{2}-[\d]{4}/', $consultationdate)){
$consult_date_arr = explode('-', $consultationdate);
}else if(preg_match('/[\d]{2}\/[\d]{2}\/[\d]{4}/', $consultationdate)){
$consult_date_arr = explode('/', $consultationdate);
}
var_dump($consult_date_arr);
?>

Hi check the code below,
<?php
if(!function_exists('date_explode')){
function date_explode($date){
$explode_date = array();
$delimiter = '';
if(strstr($date, '/')){
$delimiter = '/';
}elseif(strstr($date, '-')){
$delimiter = '-';
}
if(!empty($delimiter)){
$explode_date = explode($delimiter, $date);
}
return $explode_date;
}
}
$consult_date_arr=date_explode('22-12-2014');
print_r($consult_date_arr);
$consult_date_arr=date_explode('22/12/2014');
print_r($consult_date_arr);
?>
fiddle example
P.S.: Please do validation its a must, validation will prevent you from this type of issues

Related

How to handle spaces with preg_split in PHP

I'm getting a ftp_rawlist of files from FTP in PHP.
I take the rawlist and run this code:
foreach ($ftp_rawlist AS $ff) {
$ff = preg_split("/[\s]+/", $ff, 9);
$perms = $ff[0];
$user = $ff[2];
$group = $ff[3];
$size = $ff[4];
$month = $ff[5];
$day = $ff[6];
$file = $ff[8];
}
This works fine, but if a $ff[8] has a space at the beginning of the file name, my code doesn't parse it to $file.
E.g. " file.pdf" is parsed as "file.pdf"
I'm not sure how to modify my preg_split to capture spaces.
Try this: Remove the + symbol from the regexp by doing:
$ff = preg_split("/[\s]/", $ff, 9);
Cheers.

Variable inside regular expression php

I a stuck with regular expression and i need help.
So basically i want to do somethning like this:
$data = "hi";
$number = 4;
$reg = '/^[a-z"]{1,4}$/';
if(preg_match($reg,$data)) {
echo 'Match';
}else {
echo 'No match';
}
But i want to use variable
$reg = '/^[a-z"]{1, variable here }$/';
I have tried:
$reg = '/^[a-z"]{1, '. $number .'}$/';
$reg = "/^[a-z\"]{1, $number}$/";
But not getting right result.
Tnx for help
In the first example you have space where you shouldn't have one,
you have:
$reg = '/^[a-z"]{1, '. $number .'}$/';
your should have:
$reg = '/^[a-z"]{1,'. $number .'}$/';
then it works just fine
Update: You have same error in second example - thanks to AbraCadaver
Another way to use variables in regex is through the use of sprintf.
For example:
$nonWhiteSpace = "^\s";
$pattern = sprintf("/[%s]{1,10}/",$nonWhiteSpace);
var_dump($pattern); //gives you /[^\s]{1,10}/

str ireplace PHP parts of url

I have a html doc that has links in it.
Example :
http://mysite1.com/test/whatIwant/Idontwantthis
http://mysite1.com/test/whatIwant2/Istilldontwantthis
http://mysite1.com/test/whatIwant3/Idontwantthiseither
I want to replace these with:
http://myothersite.com/whatIwant
http://myothersite.com/whatIwant2
http://myothersite.com/whatIwant3
How can I do this? I feel like the only way is to use str_ireplace to get the value that I want and append it to the other link, I just can't seem to remove the part after the value that I want.
I use:
$var= str_ireplace("http://mysite1.com/test/", "http://myothersite.com/", $var);
But then I get the after value still on the link:
http://myothersite.com/whatIwant/Idontwantthis
I tried and now am turning to the community for help.
Thanks
Oh and they are enclosed in the tag with class and other attributes, all I need to change is the URL as explained above.
The links are not in an array they are being edited from a javascript file so they will be in a large variable as text.
$examples =
'http://mysite1.com/test/whatIwant/Idontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis
http://mysite1.com/test/whatIwant3/Idontwantthiseither'
;
Edit: using your updated example, you can split those URLs up by the whitespace between them:
$examples = 'http://mysite1.com/test/whatIwant/Idontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant2/Istilldontwantthis http://mysite1.com/test/whatIwant3/Idontwantthiseither';
$examples = explode(' ', $examples);
Alternative example array:
$examples = array(
'http://mysite1.com/test/whatIwant/Idontwantthis',
'http://mysite1.com/test/whatIwant2/Istilldontwantthis',
'http://mysite1.com/test/whatIwant3/Idontwantthiseither'
);
Regex solution:
$pattern = '/^(?:http|https):\/\/.+\/.*\/(.+)\/.*$/Um';
$replace = 'http://myothersite.com/$1';
foreach($examples as $example) {
echo preg_replace($pattern, $replace, $example);
}
Non-regex solution:
foreach($examples as $example) {
// remove the original domain name
$first = str_ireplace('http://mysite1.com/test/', '', $example);
// prepend the new domain name with the first part of the remaining URL
// e.g. strip everything after the first slash
echo 'http://myothersite.com/' . explode('/', $first)[0];
}
Note: using explode(...)[0] is array dereferencing, and is supported in PHP >= 5.4.0. For previous versions of PHP, use a variable to store the array before referencing it:
$bits = explode('/', $first);
echo 'http://myothersite.com/' . $bits[0];
From the manual:
As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.
Example output:
http://myothersite.com/whatIwant
http://myothersite.com/whatIwant2
http://myothersite.com/whatIwant3
This function should do the job.
<?php
function EditLink($link)
{
$link = explode("/",$link);
return $link[4];
}
$new_link = "http://myothersite.com/".EditLink("http://mysite1.com/test/whatIwant/Idontwantthis")."";
echo $new_link;
?>
Try this no regex:
$urls = array(
'http://mysite1.com/test/whatIwant3/Idontwantthiseither',
'http://mysite1.com/test/whatIwant/Idontwantthis',
'http://mysite1.com/test/whatIwant2/Istilldontwantthis'
);
$new_site = "http://myothersite.com/";
foreach ($urls as $url) {
$pathinfo = pathinfo($url);
$base = basename($pathinfo['dirname']);
$var = str_ireplace($url, $new_site . $base, $url);
echo $var . '<br>';
}
As of PHP 5.3:
$new_urls = array_map(function($url) { // anonymous function
global $new_site;
$pathinfo = pathinfo($url);
$base = basename($pathinfo['dirname']);
$var = str_ireplace($url, $new_site . $base, $url);
return $var;
}, $urls);
echo implode('<br>', $new_urls);
Sorry by my last answer, you was right, the order was correct.
Try this one with pre_replace, I beleave could solve the problem:
$var = "http://mysite1.com/test/whatIwant/Idontwantthis";
$var = preg_replace("/http\:\/\/mysite1.com\/([^\/]+)\/?.*/", "http://myothersite.com/$1", $var);
echo $var;

How to remove last element in php [duplicate]

This question already has answers here:
Strip off specific parameter from URL's querystring
(22 answers)
Closed 8 years ago.
I have to remove the last element in a string. I used rtrim in php but it is not working.
This is the string:
/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC
I need to remove "&make_order=ASC"
Can anyone help me?
$s = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo substr($s, 0, strrpos($s, '&'));
Edit:
$url = $base_url.trim( $_SERVER['REQUEST_URI'], "&year_order=".$arr['year_order']."" );
// ^
// |_ replace , with .
trim should work:
$string = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
$string = trim($string, "&make_order=ASC");
There's no guarantee that make_order will be at the end of the query string - or exist at all. To remove the field properly, you'd have to use something like this:
$url = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
// break down the URL into a path and query string
$parsed = parse_url($url);
// turn the query string into an array that we can manipulate
$qs = array();
parse_str($parsed['query'], $qs);
// remove the unwanted field
unset($qs['make_order']);
// rebuild the URL
$rebuilt = $parsed['path'];
if(!empty($qs)) {
$rebuilt .= '?' . http_build_query($qs);
}
echo $rebuilt;
$actual_link = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
echo str_replace("&make_order=ASC","",$actual_link);
$string = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
$args = array_pop(explode($string, "&"));
$string = implode("&", $args);
There are a bunch of ways. The easiest might be:
$i=strrpos($text,'&');
$newstring=substr($text,0,$i);
$str = "/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC";
echo $str . "<br>";
echo trim($str,"&make_order=ASC");
if &make_order=ASC is always going to be at the end, you can use strstr() to do this
$str = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo strstr($str,'&make_order=ASC',true);
Remove desired key from url.
Use:
$s = '/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100&make_order=ASC';
echo remove_key_from_url($url, 'make_order');
Output :
/search/listing.html?vehicle_type=&year=&make_name=&model_name=&loc_type=3&zipcode=641004&distance=100
Code:
function remove_key_from_url($url, $key) {
if (strpos($url, '?') === false) return $url;
list($left, $right) = explode('?', $url, 2);
parse_str($right, $get);
if (isset($get[$key])) unset($get[$key]);
return $left . '?' . http_build_query($get);
}

I want to modify the withdrawal of an array of strings where the start and end are found

I want to modify the withdrawal of an array of strings where the start and end are found
<?php
$file = ('http://gdata.youtube.com/feeds/base/users/BBCArabicNews/uploads?alt=rss&v=2&orderby=published&client=ytapi-youtube-profile');
$string=file_get_contents($file);
function findinside($start, $end, $string) {
preg_match_all('/' . preg_quote($start,'/') . '(.+?)'. preg_quote($end, '/').'/si', $string, $m);
return $m[1];
}
$start = ':video:';
$end = '</guid>';
$out = findinside($start, $end, $string);
$out = findinside($start, $end, $string);
foreach($out as $string){
echo $string;
echo "<p></td>\n";
}
?>
Results
Q80QSzgPDD8
ozei4GysBN8
ak3bbs_UxP0
rUs-r3ilTG4
p4BO6FI5sPY
j5lclrPzeVU
dK5VWTYsJaM
mERug-d536k
h0zqd3bC0-E
ije5kuSfLKY
H9XXMPvEpHM
EK5UoQqYl4U
This works properly in withdrawing of an array of strings I want to add also
$start = '</pubDate><atom:updated>';
$end = '</atom:updated>';
I want to be Show two array of strings
Example
xSD0XJLkLQid
2011-11-08T17:36:14.000Z
bFU066NwVnD
2011-12-08T17:36:14.000Z
Can I do this with this code
Greetings
You can use PHP's DOMDocument parser like this:
$objDOM = new DOMDocument();
$objDOM->load($file); // the long one from youtube
$dates = $objDOM->getElementsByTagName("pubDate");
foreach ($dates as $node)
{
echo $node->nodeValue;
}
Use a DOM parser and then a regex parser in individual elements in the DOM (using things like getElementById()). It works better and is more failsafe.

Categories