how do you parse out a text value in php - php

I have a line like this:
$line1= "System configuration: lcpu=96 mem=393216MB ent=16.00"
I need to parse out lcpu, mem and ent values from this string. I have tried something like this:
$lcpu=preg_match('/(?P<lcpu>\w+)= (?P<digit>\d+)/', $line1, $matches);
does not seem to be getting the lcpu values from the string $line1, any ideas what I am doing wrong here?

You've nearly got a query string there, so maybe
$string = explode(": ", $line1);
$string = str_replace(" ", "&", $string[1]);
parse_str($string, $values);
echo $values['lcpu'];

One other way to pares strings:
$line1= "System configuration: lcpu=96 mem=393216MB ent=16.00";
list($lcpu, $mem, $ent) = sscanf($line1, "System configuration: lcpu=%d mem=%dMB ent=%f");

Why not use a simple function to get the string between two strings. If the lcpu value is always going to be prefixed by "lcpu=" and end with a " " (space) then you could use:
function getBetween($str, $start, $end)
{
$r = explode($start, $str);
if (isset($r[1]))
{
$r = explode($end, $r[1]);
return $r[0];
}
return false;
}
and just say:
if (getBetween($line1, 'lcpu=', ' ')) { ... }
It'll return false if nothing is found.

Personally, I would parse by syntax instead (rather than searching for specific keys):
<?php
$input = "System configuration: lcpu=96 mem=393216MB ent=16.00";
// Strip out "System configuration: "
$values = preg_replace('~^.*?:\s*$~', '', $input);
// Split on whitespace separator
$values = preg_split('~\s+~', $values);
// Convert to associative array
foreach ($values as $i => $item)
{
// Explode on assignment (=)
list($k, $v) = explode('=', $item);
$values[$k] = $v;
unset($values[$i]);
}

There are many ways to parse a string. Explode is usually faster than using a regex, so this way may be more performant than the methods which rely on regular expressions.
list( , , $lcpu_pair )= explode( " ", $line1 );
list( , $lcpu_value ) = explode( "=", $lcpu_pair );
$lcpu_value will contain '96'.

Related

Is it possible to convert "x.y.z" to "x[y][z]" using regexp?

What is the most efficient pattern to replace dots in dot-separated string to an array-like string e.g x.y.z -> x[y][z]
Here is my current code, but I guess there should be a shorter method using regexp.
function convert($input)
{
if (strpos($input, '.') === false) {
return $input;
}
$input = str_replace_first('.', '[', $input);
$input = str_replace('.', '][', $input);
return $input . ']';
}
In your particular case "an array-like string" can be easily obtained using preg_replace function:
$input = "x.d.dsaf.d2.d";
print_r(preg_replace("/\.([^.]+)/", "[$1]", $input)); // "x[d][dsaf][d2][d]"
From what I can understand from your question; "x.y.z" is a String and so should "x[y][z]" be, right?
If that is the case, you may want to give the following code snippet a try:
<?php
$dotSeparatedString = "x.y.z";
$arrayLikeString = "";
//HERE IS THE REGEX YOU ASKED FOR...
$arrayLikeString = str_replace(".", "", preg_replace("#(\.[a-z0-9]*[^.])#", "[$1]", $dotSeparatedString));
var_dump($arrayLikeString); //DUMPS: 'x[y][z]'
Hope it helps you, though....
Using a fairly simple preg_replace_callback() that simply returns a different replacement for the first occurrence of . compared to the other occurrences.
$in = "x.y.z";
function cb($matches) {
static $first = true;
if (!$first)
return '][';
$first = false;
return '[';
}
$out = preg_replace_callback('/(\.)/', 'cb', $in) . ((strpos('.', $in) !== false) ? ']' : ']');
var_dump($out);
The ternary append is to handle the case of no . to replace
already answered but you could simply explode on the period delimiter then reconstruct a string.
$in = 'x.y.z';
$array = explode('.', $in);
$out = '';
foreach ($array as $key => $part){
$out .= ($key) ? '[' . $part . ']' : $part;
}
echo $out;

Only reverse the direction of consecutive Hebrew words in a string including non-Hebrew characters

I am trying to reverse a string containing Hebrew from RTL to LTR, but my coding attempt is reversing brackets as well. strrev() didn't work because it does not actually work for UTF8 strings. So I wrote a custom function, below is my code:
$str = 'תירס גדול A-10 (פרי גליל)';
function utf8_strrev($str)
{
$arr = '';
$words = explode(" ", $str);
$start_tag = '(';
$end_tag = ')';
foreach ($words as $word)
{
if (preg_match("/\p{Hebrew}/u", $word))
{
preg_match_all('/./us', $word, $ar);
echo print_r($ar[0]);
echo '<br>';
$arr = join('', array_reverse($ar[0])) . " " . $arr;
} else
{
preg_match_all('/./us', $word, $ar);
$arr = join('', $ar[0]) . " " . $arr;
}
}
return $arr;
}
OUTPUT :
)לילג ירפ( A-10 לודג סרית
what it should be:
(לילג ירפ) A-10 לודג סרית
Found this function in the comments on the docs that KoenHoeijmakers posted. I tested it, but I don't read Hebrew so it is hard for me to tell if it's working correctly.
function utf8_strrev($str){
preg_match_all('/./us', $str, $ar);
return join('',array_reverse($ar[0]));
}
Edit
Based on reading your question again, I think this works as you need it to?
function utf8_strrev($str)
{
$arr = '';
$words = explode(" ", $str);
$start_tag = '(';
$end_tag = ')';
foreach ($words as $word)
{
if (preg_match("/\p{Hebrew}/u", $word))
{
preg_match_all('/./us', $word, $ar);
$arr = join('', array_reverse($ar[0])) . " " . $arr;
} else
{
preg_match_all('/./us', $word, $ar);
$arr = join('', $ar[0]) . " " . $arr;
}
}
return preg_replace(array('/\)(.)/','/(.)\(/','/\}(.)/','/(.)\{/'),array('($1','$1)','{$1','$1}'),$arr);
}
$str='תירס גדול A-10 {פרי גליל}';
echo utf8_strrev($str);
Outut
{לילג ירפ} A-10 לודג סרית
Again, I don't read Hebrew, but hopefully it answers your question.
Note The reason I used preg_replace instead of str_replace is because the string replace method was giving me issues text like ( somthing something ( or ) something something )
I don't speak/read Hebrew, but this seems to work as desired.
I generally dislike nesting preg_ calls inside preg_ calls, but in this case, splitting the unicode characters into an array then reversing the elements prevents the need to bother with mb_encodings.
Code: (Demo)
$str = 'תירס גדול A-10 (פרי גליל)';
echo preg_replace_callback(
"/\p{Hebrew}+(?: \p{Hebrew}+)*/u",
fn($m) => implode(
array_reverse(
preg_split('~~u', $m[0], 0, PREG_SPLIT_NO_EMPTY)
)
),
$str
);
Output:
סרית A-10 (לילג ירפ)
The preg_replace_callback() pattern isolates consecutive space-delimited Hebrew words, then the anonymous function splits the multibyte letters into individual array elements, before reversing their order and joining the elements back into a single mutated string.

How to remove string with comma in a big string?

I'm a newbie in PHP ,andnow I'm struck on this problem . I have a string like this :
$string = "qwe,asd,zxc,rty,fgh,vbn";
Now I want when user click to "qwe" it will remove "qwe," in $string
Ex:$string = "asd,zxc,rty,fgh,vbn";
Or remove "fhg,"
Ex:$string = "asd,zxc,rty,vbn";
I try to user str_replace but it just remove the string and still have a comma before the string like this:
$string = ",asd,zxc,rty,fgh,vbn";
Anyone can help? Thanks for reading
Try this out:
$break=explode(",",$string);
$new_array=array();
foreach($break as $newData)
{
if($newData!='qwe')
{
$new_array[]=$newData;
}
}
$newWord=implode(",",$new_array);
echo $newWord;
In order to achieve your objective, array is your best friend.
$string = "qwe,asd,zxc,rty,fgh,vbn";
$ExplodedString = explode( "," , $string ); //Explode them separated by comma
$itemToRemove = "asd";
foreach($ExplodedString as $key => $value){ //loop along the array
if( $itemToRemove == $value ){ //check if item to be removed exists in the array
unset($ExplodedString[$key]); //unset or remove is found
}
}
$NewLook = array_values($ExplodedString); //Re-index the array key
print_r($NewLook); //print the array content
$NewLookCombined = implode( "," , $NewLook);
print_r($NewLookCombined); //print the array content after combined back
here the solution
$string = "qwe,asd,zxc,rty,fgh,vbn";
$clickword = "vbn";
$exp = explode(",", $string);
$imp = implode(" ", $exp);
if(stripos($imp, $clickword) !== false) {
$var = str_replace($clickword," ", $imp);
}
$str = preg_replace('/\s\s+/',' ', $var);
$newexp = explode(" ", trim($str));
$newimp = implode(",", $newexp);
echo $newimp;
You could try preg_replace http://uk3.php.net/manual/en/function.preg-replace.php if you have the module set up. It will allow you to optionally replace trailing or leading commas easily:
preg_replace("/,*$providedString,*/i", '', "qwe,asd,zxc,rty,fgh,vbn");

PHP: Normalize a string

I want to normalize (so canonicalize) a string into the normal form for names:
First letter of the name is uppercase
The difficulty by this is now to follow this rule with second and third name.
My method:
public function namilize($string)
{
$strings = explode(' ', $string);
foreach ($strings as $string) {
$string = ucfirst(strtolower($string));
}
$string = implode(' ', $strings);
return $string;
}
Somehow the
$string = ucfirst(strtolower($string));
fails.
What do I have to correct?
Is there a better way?
Regards
EDIT:
Hi,
thank you all for all the comments and answers.
I found another "modern" method:
public function namilize($string)
{
$string = mb_convert_case($string, MB_CASE_TITLE, mb_detect_encoding($string));
}
When I now would additionally add some regex for Mc and O's than it would be complete :)
public function namilize($name) {
$name = strtolower($name);
$normalized = array();
foreach (preg_split('/([^a-z])/', $name, NULL, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY) as $word) {
if (preg_match('/^(mc)(.*)$/', $word, $matches)) {
$word = $matches[1] . ucfirst($matches[2]);
}
$normalized[] = ucfirst($word);
}
return implode('', $normalized);
}
Note that this will work for names like John O'Brian, James McManus, etc. For other names with prefixes like McManus, simply add the prefix to the preg_match(). Obviously, this runs the possibility of false positives, but no method is going to be 100% foolproof.
You have to pass the $string by reference, note the &:
public function namilize($string)
{
$strings = explode(' ', $string);
foreach ($strings as &$string) {
$string = ucfirst(strtolower($string));
}
$string = implode(' ', $strings);
return $string;
}
Or use the function suggested by #thetaiko ucwords($string)
The $string inside the foreach will only store the last iteration (or the last name). This doesn't really matter though because the variable in the foreach is never used for output. The implode just undoes what you did with the explode so you will end up with the exact same output as the input. I changed the variable names to be more descriptive in this example:
function namilize($name_in)
{
$a_names = explode(' ', $name_in); //explode string into array
foreach ($a_names as $name) {
$a_fullname[] = ucfirst(strtolower($name)); //build array of proper case names
}
$string = implode(' ', $a_fullname); //convert array into string
return $string;
}

remove a part of a URL argument string in php

I have a string in PHP that is a URI with all arguments:
$string = http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0
I want to completely remove an argument and return the remain string. For example I want to remove arg3 and end up with:
$string = http://domain.com/php/doc.php?arg1=0&arg2=1
I will always want to remove the same argument (arg3), and it may or not be the last argument.
Thoughts?
EDIT: there might be a bunch of wierd characters in arg3 so my prefered way to do this (in essence) would be:
$newstring = remove $_GET["arg3"] from $string;
There's no real reason to use regexes here, you can use string and array functions instead.
You can explode the part after the ? (which you can get using substr to get a substring and strrpos to get the position of the last ?) into an array, and use unset to remove arg3, and then join to put the string back together.:
$string = "http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0";
$pos = strrpos($string, "?"); // get the position of the last ? in the string
$query_string_parts = array();
foreach (explode("&", substr($string, $pos + 1)) as $q)
{
list($key, $val) = explode("=", $q);
if ($key != "arg3")
{
// keep track of the parts that don't have arg3 as the key
$query_string_parts[] = "$key=$val";
}
}
// rebuild the string
$result = substr($string, 0, $pos + 1) . join($query_string_parts);
See it in action at http://www.ideone.com/PrO0a
preg_replace("arg3=[^&]*(&|$)", "", $string)
I'm assuming the url itself won't contain arg3= here, which in a sane world should be a safe assumption.
$new = preg_replace('/&arg3=[^&]*/', '', $string);
This should also work, taking into account, for example, page anchors (#) and at least some of those "weird characters" you mention but don't seem worried about:
function remove_query_part($url, $term)
{
$query_str = parse_url($url, PHP_URL_QUERY);
if ($frag = parse_url($url, PHP_URL_FRAGMENT)) {
$frag = '#' . $frag;
}
parse_str($query_str, $query_arr);
unset($query_arr[$term]);
$new = '?' . http_build_query($query_arr) . $frag;
return str_replace(strstr($url, '?'), $new, $url);
}
Demo:
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0#frag';
$string[] = 'http://domain.com/php/doc.php?arg1=0&arg2=1&arg3=0&arg4=4';
$string[] = 'http://domain.com/php/doc.php';
$string[] = 'http://domain.com/php/doc.php#frag';
$string[] = 'http://example.com?arg1=question?mark&arg2=equal=sign&arg3=hello';
foreach ($string as $str) {
echo remove_query_part($str, 'arg3') . "\n";
}
Output:
http://domain.com/php/doc.php?arg1=0&arg2=1
http://domain.com/php/doc.php?arg1=0&arg2=1
http://domain.com/php/doc.php?arg1=0&arg2=1#frag
http://domain.com/php/doc.php?arg1=0&arg2=1&arg4=4
http://domain.com/php/doc.php
http://domain.com/php/doc.php#frag
http://example.com?arg1=question%3Fmark&arg2=equal%3Dsign
Tested only as shown.

Categories