How to strip and get the code between two lines in PHP? - php

I'm trying to assign it to a variable in PHP, but all the Regex and preg_replace I've tried doesn't help me. Here is a sample text.
Claim Code:
7241B-2HWRXR9-2P2BA
$1.00
I want to pull out exactly what is in the middle, which is 7241B-2HWRXR9-2P2BA.

You can use the following to match:
Claim Code:\s*([\w-]+)\s*\$(\d+(?:\.\d+)?)
And you can pull out whatt you want by $1
See DEMO

If the code has always the same format (5-7-5 chars), you can use:
$str = 'Claim Code:
7241B-2HWRXR9-2P2BA
$1.00';
preg_match('~[\w]{5}\-[\w]{7}\-[\w]{5}~', $str, $matches);
echo $matches[0]; // returns 7241B-2HWRXR9-2P2BA
UPDATE
For optional code length this regex is possible:
preg_match('~.*:\s+([\w\-]{10,25})\s+.*~', $str, $matches);
echo $matches[1]; // ^^ here set the min and max code length, or remove it
// without setting min/max code length:
preg_match('~.*:\s+([\w\-]+)\s+.*~', $str, $matches);

Less elegant than a regexp / preg_replace, but this should work, too: Put the string into an array, then only use line 2 (array element number 1).
<?php
$string = 'Claim Code: ...............';
$lines = explode("\n", $string); //Transform the string into an array, separated by new lines (\n) (each index in the array is a single line from the string
echo $lines[1]; //this is 2nd line of the string, i.e. the claim code

Related

PHP preg_match an html arttribue with number seprated by a comma

I'm trying to get the values of an attribute and fill them in an array:
<p numbers="11.2,1.1 2,3,3.1 33"></p>
preg_match('/numbers="([0-9\\.]]+)"/',$elements,$match);
I need something like this:
$match[0] -> 11.2
$match[1] -> 1.1
$match[2] -> 2
Or anything that would get me to store the numbers in an array, but I can't figure out the regex for it.
Personally I would simply match all numbers and then split them
$matches = preg_match('/numbers="(.*)"/',$elements,$match);
$numbers = explode(',', $matches[1]);
I think I got one solution:
$string = '<tag> etc</tag>
<p numbers="11.2,1.1 2,3,3.1 33"></p>
<div> etc</div>';
// Catch only the numerals from the attribute numbers
preg_match('/<p.*numbers="(.*)"/', $string, $match);
// Catch each number separated by comma or space.
preg_match_all('/(\d+(\.?|\s?)(\d+)?)/', $match[0], $matches);
echo '<pre>';
print_r($matches[0]);
The regex is somehow pretty straightforward, but if you need some clarification, write a comment.
And you can see it tested here: https://3v4l.org/iVp1v

How to hook first hashtaged word in text

I have a PHP $var result named '$caption' result. That result sometimes have #hashtag words like Instagram or Twitter for example;
The Caipirinha is similar to a mojito, except there’s no mint … and there are a lot more limes. #Rio #Olympics #RiodeJaneiro #Caipirinha
I just want hook in text first hastagged word (bold).
In PHP how i can do (hook) first hastagged words in text($var result)?
Thanks for your answers.
You can use preg_match with a regex to match the first #word. Something like:
$string = 'The Caipirinha is similar to a mojito, except there’s no mint … and there are a lot more limes. #Rio #Olympics #RiodeJaneiro #Caipirinha';
preg_match('/#\S+/', $string, $firsthashedword);
echo $firsthashedword[0];
Should do it. \S is any non-whitespace character. The + is a quantifier meaning there must be at least one non-whitespace character after the #. Once it encounters a whitespace the match stops.
PHP Demo: https://eval.in/619122
Regex Demo: https://regex101.com/r/mE8lB6/1
<?php
$result = "This is a sample result #cool #muchwow";
$split = explode("#", $result);
$returnStr = '<b>#'.$split[1].'</b>';
echo str_replace('#'.$split[1], $returnStr, $result);
?>
Output:
This is a sample result <b>#cool</b> #muchwow
Explode will set $split to an array containing the words in between the hashtags.
So in your example the $split variable would equal ['Rio','Olympics'...etc]. Then I find the first occurrence of the '#' which would be equal to $split[1].
After I have that I perform a simple str_replace() to look for the first hashtag adding in html bold tags.
Check it out here: https://eval.in/619127

Regex matches new lines contains text after line contains only specific characters

I have a text for a book pages that may have footnotes at the end of the string like the following example:
والخاتِم بكسر التاء اسم فاعل، فكأنه قد جاء آخر الرسل، والخاتَم بفتح التاء اسم آلة، كأنه قد ختمت به الرسالة.
__________
(1) - سورة الأحزاب آية : 43.
(2) - سورة البقرة آية : 157.
(3) - سورة الأنعام آية : 17.
(4) - سورة الكهف آية : 19.
The line that I mean in the sample and the specific characters in this case are Kashidas _ (It is not dash -), in Latin, it called underscore. What I need to get is matching the four lines or any number of lines under that line.
What I have tried let only to match the first line under that line:/_.*\n*(.*)/gum and this is a demo. The only way to get them all, is to repeat the pattern portion \n*(.*) n times equals to the number of lines in the footnotes i.e four times, regarding the example case, and this is not a practical solution like this demo
You can utilize the \G anchor here:
preg_match_all('~(?:\G(?!^)|_)\R+\K[^\n]+~', $str, $matches);
print_r($matches[0]);
eval.in
Basically its not that easy to catch lines, and then every match. But what can you do is to catch everything after line, and then match again every line.
You can do that making:
/_{4,}.+/gums
/(\(.*?\.)*/gums
I hope that is good enough for you.
I just tested this successfully:
$text = "_________\r\n\r\nLine 1\r\nLine 2\r\nLine 3\r\n";
$matches = array();
$pattern = '/_+\r\n\r\n(.+)/s'; // s to have . match newlines.
// Change \r\n to \n if appropriate
// Extract all footnotes
preg_match($pattern, $text, $matches);
$footnotes = $matches[1]; // $matches[0] is the whole matched string,
// $matches[1] is the part within ()
$matches = array();
$pattern = '/(.+)/'; // Don't match newlines here
// Extract individual footnotes
preg_match_all($pattern, $footnotes, $matches);
foreach ($matches[0] as $match) { // preg_match_all returns multi-dimensional array
// Do something with each footnote
}

Regexp in php: how do I filter dynamic strings like abc/123/...?

I am trying to filter out all characters before the first / sign. I have strings like
ABC/123/...
and I am trying to filter out ABC, 123 and ... into separate strings. I have alsmost succeeded with the parsing of the first letters before the / sign except that the / sign is part of the match, which I don´t want to.
<?php
$string = "ABC/123/...";
$pattern = '/.*?\//';
preg_match($pattern, $string, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
The letters before the first/ can differ both in length and characters, so a string could also look like EEEE/1111/aaaa.
If you are trying to split the string using / as the delimiter, you can use explode.
$array = explode("/", $string);
And if you are looking only for the first element, you can use array_shift.
$array = array_shift(explode("/", $string));

Get integer value from malformed query string

I'm looking for an way to parse a substring using PHP, and have come across preg_match however I can't seem to work out the rule that I need.
I am parsing a web page and need to grab a numeric value from the string, the string is like this
producturl.php?id=736375493?=tm
I need to be able to obtain this part of the string:
736375493
$matches = array();
preg_match('/id=([0-9]+)\?/', $url, $matches);
This is safe for if the format changes. slandau's answer won't work if you ever have any other numbers in the URL.
php.net/preg-match
<?php
$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string
?>
$string = "producturl.php?id=736375493?=tm";
$number = preg_replace("/[^0-9]/", '', $string);
Unfortunately, you have a malformed url query string, so a regex technique is most appropriate. See what I mean.
There is no need for capture groups. Just match id= then forget those characters with \K, then isolate the following one or more digital characters.
Code (Demo)
$str = 'producturl.php?id=736375493?=tm';
echo preg_match('~id=\K\d+~', $str, $out) ? $out[0] : 'no match';
Output:
736375493
For completeness, there 8s another way to scan the formatted string and explicitly return an int-typed value. (Demo)
var_dump(
sscanf($str, '%*[^?]?id=%d')[0]
);
The %*[^?] means: greedily match one or more non-question mark characters, but do not capture the substring. The remainder of the format parameter matches the literal sequence ?id=, then greedily captures one or more numbers. The returned value will be cast as an integer because of the %d placeholder.

Categories