What is the simplest way to split this string using PHP? - 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 />";
?>

Related

check the same char in strg and remove and split from underscore in PHP?

Hello I have one string "22A_n22A" and i want to remove the same character from this string and want to split from "_" to two string like 22A and n22A.
i tried it but did not get any solution.
final out put i want like 22A_n22A to (n)22AA
<?php
function conti($str,$case_sensitive = false) {
//if($com1 = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $newval))
if(strcmp($case_sensitive , $case_sensitive) === 0 )
{
$pieces = explode("_", $str);
$str1 = $pieces[0];
$str2 = $pieces[1];
$ary1 = str_split($str1);
$ary2 = str_split($str2);
if (isset($case_sensitive))
{
$ary1 = array_map('strtolower',$ary1);
$ary2 = array_map('strtolower',$ary2);
}
$com = implode('',array_intersect($ary1,$ary2));
$diff = implode('',array_merge(array_diff($ary1, $ary2),array_diff($ary2, $ary1)));
$int = (int) filter_var($com, FILTER_SANITIZE_NUMBER_INT);
$onlystr = preg_replace('/\d/', '', $com);
$newval= '('.$diff.')'.$int.$onlystr.$onlystr;
// $com1 = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $str);
echo '<pre><h1>';
echo 'new value:';
print_r($newval);
echo "<br>";
echo "<br>";
echo "<br>";
echo 'new value:';
print_r($com);
echo "<br>";
echo 'new diff:';
print_r($diff);
echo '</pre>';
return $newval;
}
else {
echo '<pre><h1>';
echo 'oldvalue:';
print_r($str);
echo '</pre>';
return $str;
}
}
echo(conti('71A_n71A'));
// echo(conti('66A_n66A'));
?>
As stated in your comments your requirement is to:
Split the string on _
Pluck the last character from the first chunk of the string and append that to the end of the second string
Wrap the first character of the second chunk of the string in parentheses
For example, 65A_n66A becomes (n)66AA.
You can do this with by performing explode() on the original string, extracting the parts you need and piecing them back together in your desired format:
function format($string) {
list($first, $second) = explode('_', $string);
return sprintf('(%s)%s%s',
$second[0],
substr($second, 1),
$first[strlen($first) - 1]
);
}
This yields:
echo format('22A_n22A'); // (n)22AA
echo format('11A_n22B'); // (n)22BA
echo format('65A_n66A'); // (n)66AA
Hope this helps :)

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

Substract a part of a string considering some delimiters in php

I have a variable in php witch can have this shape:
$a = 'help&type=client';
$b = 'account#client';
$c = 'info&type=client#new';
I need to create a substract function that will work like this:
echo myFunction($a); //&type=client
echo myFunction($b); //#client
echo myFunction($c); //&type=client#new
I will rate the more simplified answere.
I think that the simplest way would be using strpbrk.
$a = 'help&type=client';
$b = 'account#client';
$c = 'info&type=client#new';
echo strpbrk($a, '&#') . PHP_EOL; //&type=client
echo strpbrk($b, '&#') . PHP_EOL; //#client
echo strpbrk($c, '&#') . PHP_EOL; //&type=client#new
myFunction would be something like this:
function myFunction($string) {
$amp = strpos($string, '&');
if($amp) {
return substr($string,$amp,strlen($string)-$amp);
} else {
$hash= strpos($string, '#');
return substr($string,$hash,strlen($string)-$hash);
}
}
You might have to change if($amp) to if($amp > 0) depending on what the output of strpos is.
What about this.
$re = "/[&#]([a-z=]+)/";
$str = "help&type=client\naccount#client";
preg_match_all($re, $str, $matches);
http://regex101.com/r/cW3yL6/1
You can use regular expressions for this
preg_match('[^help](.*)', $help, $match)
echo $match[0]; //&type=client
and
preg_match('[^account](.*)', $help, $match)
echo $match[0]; //#client
You can see this website: http://regex101.com/r/zR9eD1/1 for more information about these expressions.
Just a quick explanation:
we do NOT match 'help' and we DO match everything else (after 'help')
edit:
If you only have & or # as a delimiter you can use this:
preg_match('([#].+)', $help, $match)
echo $match[0]; //#client
This matches everything starting with a #
Use a simple preg_split:
function myFunction($var) {
return $var . "\n";
}
$a = 'help&type=client';
$b = 'account#client';
$as = preg_split('/(\w+)/', $a, 2);
$bs = preg_split('/(\w+)/', $b, 2);
echo myFunction($as[1]); // &type=client
echo myFunction($bs[1]); // #client

Preg_match_all counter?

<?
echo "Begin Function=";
echo "<br>";
$text = "2lyve: this is: 8475978474957845 948594: jfhdhfkd: just the 2lyve: beginning:";
function getTrends($text)
{
$subject = $text;
$pattern ='/(\w+:)/Ui';
preg_match_all($pattern, $subject, $matches);
foreach($matches[1] as $value)
{
print $value."<br>";
}
}
getTrends($text);
?>
The result will be:
Begin Function=
2lyve:
is:
948594:
jfhdhfkd:
2lyve:
beginning:
How do I count how many times each result is returned and rank it? Also, how to I import these results into a sql database?
PHP actually has a specific function for this purpose.
array_count_values
Your code could be changed to
<?php
echo "Begin Function=";
echo "<br>";
$text = "2lyve: this is: 8475978474957845 948594: jfhdhfkd: just the 2lyve: beginning:";
function getTrends($text)
{
$subject = $text;
$pattern ='/(\w+:)/Ui';
preg_match_all($pattern, $subject, $matches);
$findings = array_count_values($matches[1]);
foreach($findings as $value=>$occ)
{
print $value."<br>";
}
}
getTrends($text);
?>
Declare an array $map = array(); in the start of your function, and then in the place of
print $value."<br>";
put
if(isset($map[$value])) {
$map[$value]++;
} else {
$map[$value] = 1;
}

Categories