find the closest number to the first appearance of a symbol - php

<?php
$url = 'here i give a url';
$raw = file_get_contents($url);
preg_match('/\w(\d*).*?\$/',$raw,$matches);
echo $matches;
?>
in a given external website I need the closest number to the first appearance of a symbol here the symbol is $
this is what I tried for now I just get "array" printed

Am I interpreting your question correctly if you, given the following input:
<div>
<span>12.92$</span>
<span>24.82$</span>
</div>
want to get back 12.92$? I.e. you want the first occurrence of an amount of money from a web site?
If so, try the following:
// Will find any number on the form xyz.abc.
// Will NOT cope with formatting such as 12 523.25 or 12,523.25
$regex = '/(\d+(:?.\d+)?) *([$])/'
preg_match($regex, $website, $matches);
//matches[0] => 123.45$
//matches[1] => 123.45
//matches[2] => $
Another, more ambitious try (Which could fail more often) would be:
// Will find any number on the form xyz.abc.
// Attempts to cope with formatting such as 12 523.25 or 12,523.25
$regex = '/(\d{1,3}(:?[, ]?\d{3})*(:?.\d+)?) *([$])/'
preg_match($regex, $website, $matches);
//matches[0] => 12 233.45$
//matches[1] => 12 233.45
//matches[2] => $

if you get array printed > try echo $matches[0]; or echo $matches[1];
// update
// test2.php
lkadf $ lksajdf;
// test.php
$url = 'test2.php';
$raw = file_get_contents($url);
preg_match('/\w(\d*).*?\$/',$raw,$matches);
echo $matches[0]; ?>
Will output:
lkadf $ (the first part).

Use preg match with $matches[1], but you need to change your regex to
preg_match('/\w(\d+).*?\$/',$raw,$matches);
The * matches zero or more times, when really you want at least one digit. Change it to + so you match one or more.

$regex = '/([$])* (\d+(:?.\d+)?) /' ;
preg_match($regex, $str, $matches);
it works I just switched the sides for $199 !
now I need also an option to get only the second apearance:
code .....
$199 ......
....
$299
....
matches[2] should print 299

Related

Split a variable into other variables

Hello awesome people on the internet! I need some help :)
I have a php rcon script, this script saves the result of the rcon to a variable named results, this is an example.
results = Showing 2 tracked objective(s) for lluiscab:- rcon: 4 (rcon)- test: 5555 (test)
I want to set a variable like rcon to 4 and test to 5555.
I used explode and other thinks that I found on the web, but I can't make it work. Does someone know how to do it?
Edit: This variable changes, so, sometimes I can have rcon, test and coins and sometime only rcon
You can use a regular expression for this.
preg_match('/rcon:\s*(\d+).*test:\s*(\d+)/', $line, $match);
$rcon = $match[1];
$test = $match[2];
\d+ matches a sequence of numbers, and putting () around it makes it a capture group. $match contains the parts of the input line that were matched by the regular expression, and $match[N] contains the Nth capture group.
If you need to capture anything that looks like word: number, you can use preg_match_all and an associative array.
preg_match_all('/(\w+):\s*(\d+)/', $line, $matches, PREG_SET_ORDER);
$results = array();
foreach ($matches as $match) {
$results[$match[1]] = intval($match[2]);
}
For the example input, this will create
$results = array(
'rcon' => 4,
'test' => 5555
);
DEMO

Extract value from header string

I am writing a code to read bounced emails from inbox. I am getting the body of the email like so:
$body = imap_body($conn, $i);
After I get the body string, I split it into an array with explode.
$bodyParts = explode(PHP_EOL, $body);
The bounced emails that I am concerned with, they all have a particular header set i.e. X-OBJ-ID. I can loop through $bodyParts to check if that particular header is set or not, but how do I get it's value if the header exists. Currently, the header string looks like this for those bounced emails which had that header set:
"X-OBJ-ID: 24\r"
So, basically my question is: How do I extract 24 from the above string?
Lookbehinds can be helpful in such cases
/(?<=X-OBJ-ID: )\d+/
(?<=X-OBJ-ID: ) look behind. Ensures that the digits is preceded by X-OBJ-ID:
\d+ Matches digits.
Regex Demo
Example
preg_match("/(?<=X-OBJ-ID: )\d+/", "X-OBJ-ID: 24\r", $matches);
print_r($matches)
=> Array (
[0] => 24
)
Try
$int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
or you can do it via regular expression
preg_replace("/[^0-9]/","",$string);
You could do something like so:
$str = "X-OBJ-ID: 24\r";
preg_match('X-OBJ-ID:\s+(\d+)', $str, $re);
print($re);
This should match your string and store the 24 within a capture group which will be then made accessible through $re.
try this code
preg_replace('/\D/', '', $str)
it removes all the non numeric characters from the string
My solution:
<?php
$string = '"X-OBJ-ID: 24\r"';
preg_match_all('^\X-OBJ-ID: (.*?)[$\\\r]+^', $string, $matches);
echo !empty($matches[1]) ? trim($matches[1][0]) : 'No matches found';
?>
See it working here http://viper-7.com/kuMyVh

Check number ID with Preg_match

i've a little problem.
I want to check the numer of post like this:
http://xxx.xxxxxx.net/episodio/168
this is part of my code, only need the number check:
[...]
if(preg_match('#^http://horadeaventura.enlatino.net/episodio/[0-9]',trim($url))){
[...]
Can help me?
Thanks!
If you want to do it with preg_match:
$url = 'http://horadeaventura.enlatino.net/episodio/168';
if(preg_match('#^http://horadeaventura.enlatino.net/episodio/([0-9]+)#',trim($url), $matches)){
$post = $matches[1];
echo $post;
}
So, basically: I added an end delimiter (#), changed "[0-9]" to "([0-9])+", added ", $matches" to capture the matches. Of course it can be done better and using other options than preg_match. But I wanted to make your snippet work - not rewrite it.
If you don't have your heart set on using preg_match(), you could do
$string = "http://xxx.xxxxxx.net/episodio/168";
$array = explode("/", $string);
echo end($array);
which will output
168
this is assuming the number you are looking for will always be the last section of the url string
Or, you can just check for number, on last position:
if(preg_match('#[0-9]+$#',trim($url),$match)){
print_r($match);
}

Matching a substring (an apostrophe) in a given word using regex

I have a server application which looks up where the stress is in Russian words. The end user writes a word жажда. The server downloads a page from another server which contains the stresses indicated with apostrophes for each case/declension like this жа'жда. I need to find that word in the downloaded page.
In Russian the stress is always written after a vowel. I've been using so far a regex that is a grouping of all possible combinations (жа'жда|жажда'). Is there a more elegant solution using just a regex pattern instead of making a PHP script which creates all these combinations?
EDIT:
I have a word жажда
The downloaded page contains the string жа'жда. (notice the
apostrophe, I do not before-hand know where the apostrophe in the
word is)
I want to match the word with apostrophe (жа'жда).
P.S.: So far I have a PHP script creating the string (жа'жда|жажда') used in regex (apostrophe is only after vowels) which matches it. My goal is to get rid of this script and use just regex in case it's possible.
If I understand your question,
have these options (d'isorder|di'sorder|dis'order|diso'rder|disor'der|disord'er|disorde'r|disorder‌​') and one of these is in the downloaded page and I need to find out which one it is
this may suit your needs:
<pre>
<?php
$s = "d'isorder|di'sorder|dis'order|diso'rder|disor'der|disord'er|disorde'r|disorder'|disorde'";
$s = explode("|",$s);
print_r($s);
$matches = preg_grep("#[aeiou]'#", $s);
print_r($matches);
running example: https://eval.in/207282
Uhm... Is this ok with you?
<?php
function find_stresses($word, $haystack) {
$pattern = preg_replace('/[aeiou]/', '\0\'?', $word);
$pattern = "/\b$pattern\b/";
// word = 'disorder', pattern = "diso'?rde'?r"
preg_match_all($pattern, $haystack, $matches);
return $matches[0];
}
$hay = "something diso'rder somethingelse";
find_stresses('disorder', $hay);
// => array(diso'rder)
You didn't specify if there can be more than one match, but if not, you could use preg_match instead of preg_match_all (faster). For example, in Italian language we have àncora and ancòra :P
Obviously if you use preg_match, the result would be a string instead of an array.
Based, on your code, and the requirements that no function is called and disorder is excluded. I think this is what you want. I have added a test vector.
<pre>
<?php
// test code
$downloadedPage = "
there is some disorde'r
there is some disord'er in the example
there is some di'sorder in the example
there also' is some order in the example
there is some disorder in the example
there is some dso'rder in the example
";
$word = 'disorder';
preg_match_all("#".preg_replace("#[aeiou]#", "$0'?", $word)."#iu"
, $downloadedPage
, $result
);
print_r($result);
$result = preg_grep("#'#"
, $result[0]
);
print_r($result);
// the code you need
$word = 'also';
preg_match("#".preg_replace("#[aeiou]#", "$0'?", $word)."#iu"
, $downloadedPage
, $result
);
print_r($result);
$result = preg_grep("#'#"
, $result
);
print_r($result);
Working demo: https://eval.in/207312

stuck in regular expression i dont know if it is even possible or not using php preg_match_all

i have a file out of which i want a specific data below is the sample data
moduleHelper.addModule('REC');
moduleHelper.addModule('TOP');
What i want is
anything.anything('x');i.e.
moduleHelper.addModule('');
The above is what i want to be returned .
i just dont want the 'x' part exclusive of single quote.
i tried by my self and wrote a regex which is below.
/(.*)\.(.*)\(\'[^.*]\'\)/mi
it gives me nothing according to the PCRE manual the ^ inside the [ ] does negation ??
It could be done with preg_replace_callback if you feel like figuring out how all that backreferencing works, but i think this is a bit easier:
// the regex
$regex = "/(?P<FIRST>.+)?\.(?P<SECOND>.+)\('(?P<PARAM>.+)?\'\)?/mi";
$subject = <<<EOB
moduleHelper.addModule('REC');
moduleHelper.addModule('TOP');
EOB;
$matches = array();
$numberOfMatches = preg_match_all($regex, $subject, $matches, PREG_SET_ORDER);
$results = array();
foreach($matches as $match)
{
array_push($results, sprintf("%s.%s('')", $match['FIRST'], $match['SECOND']));
}
print_r($results);
// result:
Array
(
[0] => moduleHelper.addModule('')
[1] => moduleHelper.addModule('')
)
Try using the following
/^([^.]+)\.([^\(]+)/
If ^ is the first character in [ ] then it negates the other characters in the set. Where [ab] accepts either a or b, [^ab] accepts any character that is not a nor b.
Also I'm not sure what you want. You state that you do not want the 'x', but what exactly do you want?
It does do negation. [^.*], in this case, means "get on character that is not . or *. I think you want below, but I can't totally tell.
preg_match_all( "/(\w+\.\w+)(?=\([\"']\w+[\"']\);)/i", $string, $matches);
Try this one:
/([^.]*)\.([^.]*)\(.*\)/

Categories