Extract 2 sets of numbers from a string using PHP's preg? - php

Here's some PHP code:
$myText = 'ABC #12345 (2009) XYZ';
$myNum1 = null;
$myNum2 = null;
How do I add the first set of numbers from $myText after the # in to $myNum1 and the second numbers from $myText that are in between the () in to $myNum2. How would I do that?

preg_match('/#(\d+).*\((\d+)\)/', $myText, $matches);
$myNum1 = $matches[1];
$myNum2 = $matches[2];
assuming you have something like:
" stuff ... #123123 stuff (456456)"
that will give you
$myNum1 = 123123
$myNum2 = 456456

If you have an input string of form "123#456", you can do
$tempArray = explode("#", $input);
if (sizeof($tempArray) != 2) {
echo "OH NO! Something bad happened!";
}
$value1 = intval($tempArray[0]);
$value2 = intval($tempArray[1]);
echo "Result: " . ($value1 + $value2);

Related

Question about REGEX extracting text beetween

I'm trying in PHP to get something like this:
$mail = "fakemail#le.mail.uk.test";
$rep = "le.mail";
I tried like this:
function test($mail) {
$pattern = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/';
preg_match($pattern, $mail, $matches);
echo $matches[2] . "\n";
}
test("fakemail#le.mail.uk");
// result = le.mail
but if i have another . in my mail it's broken
function test($mail) {
$pattern = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/';
preg_match($pattern, $mail, $matches);
echo $matches[2] . "\n";
}
test("fakemail#le.mail.uk.test.test");
// result = le.mail.uk.test.test.test
// whatIwant = le.mail
or I just want all character between # and until the next ..
I think I have to do a loop with an if but I'm not sure if it's possible
with only regex.
A php way without REGEX, using implode() and explode()
<?php
$sep = '.';
$str1 = 'email#test.com.robot';
$str2 = 'email#test.fr.uk.robot';
$get1 = explode($sep,explode('#',$str1)[1]);
$get2 = explode($sep,explode('#',$str2)[1]);
echo implode($sep,[$get1[0],$get1[1]]);
echo PHP_EOL;
echo implode($sep,[$get2[0],$get2[1]]);
?>
Output:
test.com
test.fr
DEMO: https://3v4l.org/hJu52

PHP function to lowercase each character in a string except for the last one

I'm trying to lowercase every character in a string except for the last one that should be in uppercase.
Here is my code:
function caps_caps($var) {
$var = strrev(ucwords(strrev($var)));
echo $var;
}
caps_caps("HeLlo WOrld"); // should returns "hellO worlD"
This is the easy solution of this problem
function caps_caps($var) {
$var = strrev(ucwords(strrev(strtolower($var))));
echo $var;
}
caps_caps("HeLlo WOrld");
Demo
You also need to convert the string to lowercase first.
function caps_caps($var) {
$var = strrev(ucwords(strrev(strtolower($var))));
echo $var;
}
caps_caps("HeLlo WOrld"); // returns "hellO worlD"
function caps_caps($text) {
$value_to_print = '';
$text = strrev(ucwords(strrev($text)));
$words = explode(' ', $text);
foreach($words as $word){
$word = strtolower($word);
$word[strlen($word)-1] = strtoupper($word[strlen($word)-1]);
$value_to_print .= $word . ' ';
}
echo trim($value_to_print);
}
caps_caps("HeLlo WOrld");
You can try this piece of code.
function uclast($s)
{
$lastCharacterUppar = '';
if ( preg_match('/\s/',$s) ){//If string has space
$explode = explode(' ',$s);
for($i=0;$i<count($explode);$i++){
$l=strlen($explode[$i])-1;
$explode[$i] = strtolower($explode[$i]);
$explode[$i][$l] = strtoupper($explode[$i][$l]);
}
$lastCharacterUppar = implode(' ', $explode);
} else { //if string without space
$l=strlen($s)-1;
$s = strtolower($s);
$s[$l] = strtoupper($s[$l]);
$lastCharacterUppar = $s;
}
return $lastCharacterUppar;
}
$str = 'hey you yo';
echo uclast($str);
Try this, you forgot to do foreach, each elements.
function uclast_words($text, $delimiter = " "){
foreach(explode($delimiter, $text) as $value){
$temp[] = strrev(ucfirst(strrev(strtolower($value))));
}
return implode($delimiter, $temp);
}
print_r(uclast_words("hello world", " "));
I hope this is the answer of your question.
Here is a multibyte safe technique that performs the title-casing with one call instead of two. The string reversal and re-reversal is still necessary.
Code: (Demo)
echo strrev(
mb_convert_case(
strrev('HeLlo WOrld'),
MB_CASE_TITLE
)
);
// hellO worlD

How to find out if there is any redundant word in string in php?

I need to find out if there are any redundant words in string or not .Is there any function that can provide me result in true/false.
Example:
$str = "Hey! How are you";
$result = redundant($str);
echo $result ; //result should be 0 or false
But for :
$str = "Hey! How are are you";
$result = redundant($str);
echo $result ; //result should be 1 or true
Thank you
You could use explode to generate an array containing all words in your string:
$array = explode(" ", $str);
Than you could prove if the arrays contains duplicates with the function provided in this answer:
https://stackoverflow.com/a/3145660/5420511
I think this is what you are trying to do, this splits on punctuation marks or whitespaces. The commented out lines can be used if you want the duplicated words:
$str = "Hey! How are are you?";
$output = redundant($str);
echo $output;
function redundant($string){
$words = preg_split('/[[:punct:]\s]+/', $string);
if(max(array_count_values($words)) > 1) {
return 1;
} else {
return 0;
}
//foreach(array_count_values($words) as $word => $count) {
// if($count > 1) {
// echo '"' . $word . '" is in the string more than once';
// }
//}
}
References:
http://php.net/manual/en/function.array-count-values.php
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.preg-split.php
Regex Demo: https://regex101.com/r/iH0eA6/1

What is the simplest way to split this string using PHP?

I have the below string in PHP.
:guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP
I need to create these variables from the string:
$nick = guest
$user = lbjpewueqi
$host = AF8A326D.E0B4A40D.F85DC93A.IP
What is the best function to use to do this?
Ideally I would like to create some sort of function so I can pass to it the string and what part I want returned.
For example:
$string = "guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
echo stringToPart($string, nick);
guest
echo stringToPart($string, nick);
lbjpewueqi
echo stringToPart($string, host);
AF8A326D.E0B4A40D.F85DC93A.IP
Another version:
function stringToPart($string, $part) {
if (preg_match('/^:(.*)!(.*)#(.*)/', $string, $matches)) {
$nick = $matches[1];
$user = $matches[2];
$host = $matches[3];
return isset($$part) ? $$part : null;
}
}
More strict than preg_split solutions - it checks separators order.
Maybe this code may helpful for you
$p = '/[:!#]/';
$s = ":guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
print_r( preg_split( $p, $s ), 1 );
You can declare a function like this:
$s = ":guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
function stringToPart($str, $part) {
$pat['nick'] = '/:(.*)!/';
$pat['user'] = '/.*!(.*)#/';
$pat['host'] = '/#(.*)/';
preg_match($pat[$part], $str, $m);
if (count($m) > 1) return $m[1];
return null;
}
echo stringToPart($s,'nick')."\n";
echo stringToPart($s,'user')."\n";
echo stringToPart($s,'host')."\n";
The below should do what you're looking for.
$pattern = "/[:!#]/";
$subject = ":guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
print_r(preg_split($pattern, $subject));
The pattern is specifying what characters to split on so you could in theory have any amount of characters here if there were other instance you needed to account for different strings being passed in.
To return the values instead of just printing then to the screen use this:
$pattern = "/[:!#]/";
$subject = ":guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP";
$result = preg_split($pattern, $subject));
$nick = $result[1];
$user = $result[2];
$host = $result[3];
stringToPart(':guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP','nick');
function stringToPart($string, $type){
$result['nick']= substr($string,strpos($string,':')+1,(strpos($string,'!')-strpos($string,':')-1));
$result['user']= substr($string,strpos($string,'!')+1,(strpos($string,'#')-strpos($string,'!')-1));
$result['host']= substr($string,strpos($string,'#')+1);
return $result[$type];
}
<?php
function stringToPart($string, $key)
{
$matches = null;
$returnValue = preg_match('/:(?P<nick>[^!]*)!(?P<user>.*?)#(?P<host>.*)/', $string, $matches);
if (isset($matches[$key]))
{
return $matches[$key];
} else
{
return NULL;
}
}
$string = ':guest!lbjpewueqi#AF8A326D.E0B4A40D.F85DC93A.IP';
echo stringToPart($string, "nick");
echo "<br />";
echo stringToPart($string, "user");
echo "<br />";
echo stringToPart($string, "host");
echo "<br />";
?>

String translate from Array , str_replace?

String translate from Array , str_replace?
I have an array
$money = array(
"USD"=>100,
"BAT"=>1000,
"RIEL"=>2000
);
And I define as constant to be translate:
define("const_infor","Your __TYPE__ are: __AMOUNT__ __CURRENCY__ .<br><br>");
Bad WAYS:
echo "Your balance are :";//more constant here
foreach ($money as $currency=>$amount){
echo $money.$currency."; ";
}
I try to output(GOOD WAYS):
$tmp1 = "";
$tmp2 = "";
foreach ($money as $currency=>$amount){
$tmp1 .= $money;
$tmp2 .= $currency;
}
echo str_replace(ARRAY("__TYPE__","__AMOUNT__","__CURRENCY__"),ARRAY("Balance",$tmp1,$tmp2),const_infor);
BUT What I want is the output should be :
Your Balance are: 100 USD; 1000 BAT; 2000 RIEL
How can I pass the $currency. to str_replace ?
Anyone can help me to do this.?
I don't know what exactly you wanna do but if it's only output
try
printf("Your Money %f %f %f", $money["USD"], $money["BAT"], $money["RIEL"]);
Well, below is just kind of a parser for doing what you want.. Try and see if it fits your needs:
function replace($string, $name = '', $value = '')
{
if ( !empty($name) )
{
str_replace('{'.$name.'}', $value, $string);
}
}
$string = 'Your balance is {bal1} USD, {bal2} BAT';
$string = replace('bal1', $money['USD'], $string);
$string = replace('bal2', $money['BAT'], $string);
$string = replace('bal3', $money['GBP'], $string);
print $string;
try that:
foreach ($money as $key => $cur)
echo $cur.' '. $key;

Categories