preg_match strings regardless of proper format - php

I have this kind of string format used in a preg_match:
[Day][MonthAbbr] [Date] [Hour]:[Minutes][AM/PM]
example:
ThuDec 27 2:00am
Having this $pattern and some sort of code:
$pattern = "/([A-Z]{2}\w+)([A-Z]{2}\w+)\s+(\w+)\s+(\d+):(\d+)(..)/ims";
$match = array();
if (preg_match($pattern, rtrim($date), $match)) {
echo '<pre>';
print_r($match);
echo '</pre>';
} else {
echo 'Could not parse date.';
}
i was able to extract the Month, Day, Time, etc... from the string..
But i was wondering why i came up with the catch 'Could not parse date.' even if the value being passed was still the same..
I compared the values and the one which has an error:
ThuDec 27 2:00am
ThuDec 27 4:30am (gives the error)
Here's the screen shot below to make a comparison:
Is there something wrong with the pattern ive been using in the preg_match?

<?php
$a = "ThuDec 27 4:30am";
$pattern = "/([a-z]{3})([a-z]{3})\s+(\d+)\s+(\d+):(\d+)([a-z]{2})/i";
$match = array();
if (preg_match($pattern, $a, $match)) {
echo '<pre>';
print_r($match);
echo '</pre>';
} else {
echo 'Could not parse date.';
}
?>
This code works pretty well for me.

Related

php extract a sub-string before and after a character from a string

need to extract an info from a string which strats at 'type-' and ends at '-id'
IDlocationTagID-type-area-id-492
here is the string, so I need to extract values : area and 492 from the string :
After 'type-' and before '-id' and after 'id-'
You can use the preg_match:
For example:
preg_match("/type-(.\w+)-id-(.\d+)/", $input_line, $output_array);
To check, you may need the service:
http://www.phpliveregex.com/
P.S. If the function preg_match will be too heavy, there is an alternative solution:
$str = 'IDlocationTagID-type-area-id-492';
$itr = new ArrayIterator(explode('-', $str));
foreach($itr as $key => $value) {
if($value === 'type') {
$itr->next();
var_dump($itr->current());
}
if($value === 'id') {
$itr->next();
var_dump($itr->current());
}
}
This is what you want using two explode.
$str = 'IDlocationTagID-type-area-id-492';
echo explode("-id", explode("type-", $str)[1])[0]; //area
echo trim(explode("-id", explode("type-", $str)[1])[1], '-'); //492
Little Simple ways.
echo explode("type-", explode("-id-", $str)[0])[1]; // area
echo explode("-id-", $str)[1]; // 492
Using Regular Expression:
preg_match("/type-(.*)-id-(.*)/", $str, $output_array);
print_r($output_array);
echo $area = $output_array[1]; // area
echo $fnt = $output_array[2]; // 492
You can use explode to get the values:
$a = "IDlocationTagID-type-area-id-492";
$data = explode("-",$a);
echo "Area ".$data[2]." Id ".$data[4];
$matches = null;
$returnValue = preg_match('/type-(.*?)-id/', $yourString, $matches);
echo($matches[1]);

'Array' showing in my foreach loop

For some reason I'm getting the word 'array' as an output when I try to do a foreach to echo out the values in an array (there are 2 values). These show fine if I use print_r in the array so I know they are there. I've also tried using as list but that only shows the first value and nothing after it.
It's getting late so it might be something pretty silly! Thanks in advance
<?php
$crawl_url = "./emails.php";
function get_email($url) {
$input = #file_get_contents($url);
$regexp = '/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/i';
preg_match_all($regexp, $input, $matches);
if (empty($input)) {
echo "No email addresses found";
}
else {
foreach($matches as $matches_values) {
print $matches_values;
}
}
}
get_email($crawl_url);
echo '<br /> function complete';
?>
I think you're missing the 0 index on $matches.
Try this :
foreach($matches[0] as $matches_values) {
print $matches_values;
}

Identify a blank line in a text area

I am trying to identify a blank lines in a string. Below is my attempt in PHP:
<?php
$alldevs = $_POST['devs'];
$devices = explode("\n", $alldevs);
foreach($devices as $device) {
if(!empty($device)){
echo $device;
} else {
echo "end of value";
}
}
?>
When I input the following:
1
2
3
4
I get this output:
1
2
3
4
But what it should be outputting is this:
1
2
3
end of value
end of value
4
What am I doing wrong?
They probably contain a \r (which is posted on new lines in text areas for some browsers/OS'es), a space or a tab character. You can get rid of these by using the trim() command:
<?php
$alldevs = $_POST['devs'];
$devices = explode("\n", $alldevs);
foreach ($devices as $device) {
$device = trim($device); //Trim that string!
if(!empty($device))
{
echo $device;
}
else
{
echo "end of value";
}
}
?>
Oh, and PLEASE indent your code for your own and everybody elses sake.
Alternatively, split up your string by using regex:
$devices = preg_split("/(\r\n|\n\r|\r|\n)/", $alldevs);
This should give you what you want:
if( trim($device) !== '' )
{
echo $device."<br>";
}
else
{
echo "end of value"."<br>";
}
Outputs:
1
2
3
end of value
4
I think your problem is with \r\n
Use this code
$alldevs = str_replace("\r", '', $alldevs);
Then explode it, and also use trim for clean spaces
$alldevs = trim($alldevs);
first, please read dealing with line endings and wikipedia newline
second, you are using string explode when you should use a function like preg_match_all
code should look something like this (mind the bad regex please):
<?php
$string = $_POST['devs'];
preg_match_all('%^([^\n\r]*)[\n\r]?$%im', $string, $matches);
foreach ($matches[1] as $match) {
if($match) {
var_dump($match);
} else {
echo 'empty line' . PHP_EOL;
}
}
adjust this code to fit your needs, i left a var_dump there so you could see the string length.
Add a check for a string with more than 0 characters,
if(!empty($device) && strlen($device)>0) {
I would also try a use case with \r\n on your line-breaks, you'll run into that as well.
you can try this
$devices = preg_replace('/^\s*$/','end of value',explode("\n",$alldevs));
foreach($devices as $device) {
echo $device, "\n";
}

find a specific word in external page

How to find a specific word in a external page using php ?
(dom or pregmatch, or what else ?)
example in foo.com source code with :
span name="abcd"
I want to check if the word abcd is in foo.com in php
if(preg_match('/span\s+name\=\"abcd\"/i', $str)) echo 'exists!';
To check if a string of characters exist:
<?php
$term = 'abcd';
if ( preg_match("/$term/", $str) ) {
// yes it does
}
?>
To check if that string exists as a word in its own right (ie, is not in the middle of a larger word) use word boundary matchers:
<?php
$term = 'abcd';
if ( preg_match("/\b$term\b/", $str) ) {
// yes it does
}
?>
For a case-insensitive search, add the i flag after the last slash in the regex:
<?php
$term = 'abcd';
if ( preg_match("/\b$term\b/i", $str) ) {
// yes it does
}
?>
$v = file_get_contents("http://foo.com");
echo substr_count($v, 'abcd'); // number of occurences
//or single match
echo substr_count($v, ' abcd ');
Here are other few ways to find specific word
<?php
$str = 'span name="abcd"';
if (strstr($str, "abcd")) echo "Found: strstr\n";
if (strpos($str, "abcd")) echo "Found: strpos\n";
if (ereg("abcd", $str)) echo "Found: ereg\n";
if (substr_count($str, 'abcd')) echo "Found: substr_count\n";
?>
$name = 'foo.php';
file_get_contents($name);
$contents=$pattern = preg_quote('abcd', '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo implode("\n", $matches[0]);
}
else{
echo "not exist word";
}

PHP Form Question

Is there a way I can check if a user enters a <p> tag inside a form using PHP?
If you simply want to strip all markup use:
strip_tags ( string $str [, string $allowable_tags ] )
otherwise:
substr_replace ( $string , string $replacement , int $start [, int $length ] )
Depends on why you what to know
1 - PHP.net
If it is posted, you can do something like strstr of '<p>' or one of the similar functions, which will then return the location if it exists or NULL if it doesn't.
<?php if ( strstr ( $body, '<p>' ) == NULL )
echo 'All Clear';
else die ( 'Contains <p>' );
if(empty($_POST['foo'])) {
print "Foo empty";
} else {
if(stristr($_POST['foo'], '<p>')) {
print "Contains P tag";
} else {
print "No P tag";
}
}
You could use javascript or jquery .onFocus event.
Assuming they don't enter anything fancy like <p class="stuff">, you can use a simple strpos() call:
$text = $_POST['name_of_field'];
if (strpos($text, '<p>') !== FALSE) {
die("No <p> tags allowed");
}
If they enter attributes, then you'd most likely need a regex, which has its own basket of problems:
$text = $_POST['name_of_field'];
if (preg_match('/<p.*?>/i', $text)) {
die("No <p> tags allowed");
}
Is this what you mean? Assuming you have the form content in a string variable, something like this should work:
<?php
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL | E_STRICT);
$string1 = 'Hello <p> world';
$string2 = 'Hello world';
$foundIt1 = strripos($string1, '<p>');
$foundIt2 = strripos($string2, '<p>');
if (false === $foundIt1) {
echo '1. didn\'t find it';
} else {
echo "1. found it at offset $foundIt1";
}
echo "\n";
if (false === $foundIt2) {
echo '2. didn\'t find it';
} else {
echo "2. found it at offset $foundIt2";
}
?>
If you want to replace or remove them:
$new_data = preg_replace("/<p>/", "whatever you want to replace it with here", $_POST['form_field_id_here']);
If you just want to check for them
strpos("<p>", $_POST['form_field_id_here']);
Then read this to make sure you aren't leaving your site open to attackers:
What's the best method for sanitizing user input with PHP?
(Edit: I know, I know. No regex for HTML parsing. IMHO, if all you are doing is checking for tags then a little bit of regex is better than using a huge HTML parser. That said, if you are checking for many tags and things like <p class="something"> then you should look at this: http://docs.php.net/manual/en/domdocument.loadhtml.php )

Categories