Return part of string - php

I have an array with strings like:
209#ext-local : SIP/209 State:Idle Watchers 2
208#ext-local : SIP/208 State:Unavailable Watchers 1
How can I echo the state for example Idle or Unavailable?
Thanks.

Using regex it will match any string containing letters and numbers.
$string = '209#ext-local : SIP/209 State:Idle Watchers 2';
preg_match("/State\:([A-Za-z0-9]+)/", $string, $results);
echo $results[1]; // Idle

strpos will search the string to see if it is contains the characters in that exact order.
strpos will not always work if the word idle or unavailable has the possibility to show up in any other way in the string.
You can use the php explode and parse the sting into an array of strings.
exp.
$string = "209#ext-local : SIP/209 State:Idle Watchers 2";
$string = explode(':', $string);
will give you ['209#ext-local ',' SIP/209 State','Idle Watchers 2']. Then if you explode the 3rd entry my ' ' you would get your answer.
$answer = explide(' ', $string[2]);
echo $answer[0];

Assuming your strings are all the same format, you can try splitting the string down using explode(), which returns an array of string, separated by a provided delimiter, like
foreach ($yourStrings as $s) {
$colonSplit = explode(":", $stringToSplit);
$nextStringToSplit = $colonSplit[2];
$spaceSplit = explode(" ", $nextStringToSplit);
$status = $spaceSplit[0];
echo $status;
}
May not be elegant but it should work.

Quick (and dirty) way. Assuming your array contains the full elements you listed above, the array element values do NOT contain 'idle' or 'unavailable' in any other capacity other than what you listed, and you just want to echo out the value and "is idle" or "is unavailable":
//$a being your array containing the values you listed above
foreach ($a as $status) {
if (strpos($status, "Idle") == true)
echo $status . " is idle";
elseif (strpos($status, "Unavailable") == true)
echo "$status" . " is unavailable";
}

Related

Check if input variables are numbers in an array

The problem is the following in PHP:
How to check if the input variables are numbers in an array if all of them was asked to separate with a " " (space) character within a form?
is_int and is_numeric don't work here, since it's a string not an array.
The answer might be easy, I'm just struggling with it in these late night hours.
The whole problem:
By using only one input field, read in numbers separated by " "(space), then print them out in ascending order. If there is any other variable besides numbers, print "error".
$str = "999 999 999 99";
$arr = explode(" ", $str);
foreach ($arr as $value) {
if(is_numeric($value)){
echo 'ok';
}
}
Might just replace the spaces:
if(is_numeric(str_replace(' ', '', $input)) {
// $input without spaces is numeric
}

count the occurrences of all the letters in a string PHP

I want to count the frequency of occurrences of all the letters in a string. Say I have
$str = "cdcdcdcdeeeef";
I can use str_split and array_count_values to achieve this.
array_count_values(str_split($str));
Wondering if there is another way to do this without converting the string to an array? Thanks
You don't have to convert that into an array() you can use substr_count() to achieve the same.
substr_count — Count the number of substring occurrences
<?php
$str = "cdcdcdcdeeeef";
echo substr_count($str, 'c');
?>
PHP Manual
substr_count() returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.
EDIT:
Sorry for the misconception, you can use count_chars to have a counted value of each character in a string. An example:
<?php
$str = "cdcdcdcdeeeef";
foreach (count_chars($str, 1) as $strr => $value) {
echo chr($strr) . " occurred a number of $value times in the string." . "<br>";
}
?>
PHP Manual: count_chars
count_chars — Return information about characters used in a string
There is a php function that returns information about characters used in a string: count_chars
Well it might not be what you are looking for, because according to http://php.net/manual/en/function.count-chars.php it
Counts the number of occurrences of every byte-value (0..255) in
string and returns it in various ways
Example from same link (http://php.net/manual/en/function.count-chars.php):
<?php
$data = "Two Ts and one F.";
foreach (count_chars($data, 1) as $i => $val) {
echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n";
}
?>
class Strings
{
public function count_of_each_letter($string){
$string_chars = array();
$length_ = mb_strlen($string,'UTF-8');
if($length_== 0){return null;}
else{
for ($i=0; $i < $length_; $i++) {
$each_letter = mb_substr($string,0,1,'UTF-8');
$string_chars[$each_letter] = mb_substr_count($string, $each_letter);
$string = str_replace($each_letter,"", $string);
$length_ = mb_strlen($string,'UTF-8');
}
$string = '';
foreach ($string_chars as $key => $value) {
$string .= $key.'-'.$value.'<br>';
}
return $string;
}
}
}
$new_counter = new Strings();
echo $new_counter::count_of_each_letter('ختواجرایآهنگبهصورتتکنفرهنمود.اوازسال۱۹۷۲تا۱۹۷۵،۴آلبوماستودیوییتک‌نفرهمنتشرکردوحتینامزدیکجایزهاسکارهمشد.درهمینسال‌هاگروهاقدامبهبرگزاریتورکنسرتدراروپاونیزیکتورجهانیکردند.جکسونفایودرسال۱۹۷۵ازشرکتنشرموسیقیموتاونرکوردزبهسی‌بی‌اسرکوردزنقلمکانکردند.گروههمچنانبهاجراهایبین‌المللیخودادامهمی‌دادواز۱۹۷۶تا۱۹۸۴(از۱۵تا۲۴سالگیمایکل)ششآلبوماستودیوییدیگرمنتشرکرد.درهمینمدت،مایکلترانه‌سرایاصلیگروهجکسونزبود.Cantional,oderGesangbuchAugsburgischerKonfessionin1627.ohannSebastianBachcomposedafour-partsetting,BWV285,whichiswithouttext.twaspublishedasNo.196inthecollectionofchoralesbyJohannPhilippKirnbergerundCarlPhilippEmanufread');
you can do it by following way as well:
$str = 'aabbbccccdddeeedfff';
$arr = str_split($str);
$result = array_count_values($arr);
$string = http_build_query($result,'','');
echo str_replace('=','',$string);

How to check if comma separated strings have duplicate values in php

I have a variable that contains comma separated strings and I would like to create a check if this variable has duplicate strings inside without converting it into an array. If it would make it any easier, each comma separated strings have 3 characters.
example.
$str = 'PTR, PTR, SDP, LTP';
logic: if any of the strings has a duplicate value then display an error.
This should work for you:
Just use strtok() to loop through each token of your string, with , as delimiter. Then use preg_match_all() to check if the token is more than once in the string.
<?php
$str = "PTR, PTR, SDP, LTP";
$tok = strtok($str, ", ");
$subStrStart = 0;
while ($tok !== false) {
preg_match_all("/\b" . preg_quote($tok, "/") . "\b/", substr($str, $subStrStart), $m);
if(count($m[0]) >= 2)
echo $tok . " found more than 1 times, exaclty: " . count($m[0]) . "<br>";
$subStrStart += strlen($tok);
$tok = strtok(", ");
}
?>
output:
PTR found more than 1 times, exaclty: 2
You are going to run into some issues with just using explode. In your example, if you use explode, you'll get:
'PTR', ' PTR', ' SDP', ' LTP'
You have to map trim in there.
<?php
// explode on , and remove spaces
$myArray = array_map('trim', explode(',', $str));
// get a count of all the values into a new array
$stringCount = array_count_values($myArray);
// sum of all the $stringCount values should equal size of $stringCount IE: they are all 1
$hasDupes = array_sum($stringCount) != count($stringCount);
?>

Check if URL contains string then create variables with url strings

I need to check if URL contains the term: "cidades".
For example:
http://localhost/site/cidades/sp/sorocaba
So, if positive, then I need to create two or three variables with the remaining content without the " / ", in this case:
$var1 = "sp";
$var2 = "sorocaba";
These variables will be cookies values in the beggining of the page, then, some sections will use as wp-query these values to filter.
This should work for you:
Here I check with preg_match() if the search word is in the url $str between two slashes. If yes I get the substr() from the url after the search word and explode() it into an array with a slash as delimiter. Then you can simply loop through the array an create the variables with complex (curly) syntax.
<?php
$str = "http://localhost/site/cidades/sp/sorocaba";
$search = "cidades";
if(preg_match("~/$search/~", $str, $m, PREG_OFFSET_CAPTURE)) {
$arr = explode("/", substr($str, $m[0][1]+strlen($m[0][0])));
foreach($arr as $k => $v)
${"var" . ($k+1)} = $v;
}
echo $var1 . "<br>";
echo $var2;
?>
output:
sp
sorocaba
Here are two functions that will do it for you:
function afterLast($haystack, $needle) {
return substr($haystack, strrpos($haystack, $needle)+strlen($needle));
}
And PHP's native explode.
First call afterLast, passing the /cidades/ string (or just cidades if you don't expect the slashes). Then take the result and explode on / to get your resulting array.
It would look like:
$remaining_string = afterLast('/cidades/', $url);
$items = explode('/', $remaining_string)
Just note that if you do not include the / marks with the afterLast call, your first element in the explode array will be empty.
I think this solution is better, since the resulting array will support any number of values, not just two.

Find exact string in string - PHP

How do I find exact 2, in a string using strpos? Is it possible using strpos? The example below returns "Found" even though the match is NOT exact to what I need. I understand 2, is matching with 22,. It should return "Not Found". I am matching ID's in this example.
$string = "21,22,23,26,";
$find = "2,";
$pos = strpos($string, $find);
if ($pos !== false) {
echo "Found";
} else {
echo "Not Found";
}
Unless the string is enormous, make an array and search it:
$string = "21,22,23,26,";
$arr = explode(",", $string);
// array_search() returns its position in the array
echo array_search("2", $arr);
// null output, 2 wasn't found
Actually, in_array() is probably faster:
// in_array() returns a boolean indicating whether it is found or not
var_dump(in_array("2", $arr));
// bool(false), 2 wasn't found
var_dump(in_array("22", $arr));
// bool(true), 22 was found
This will work as long as your string is a comma-delimited list of values. If the string is really long, making an array may be wasteful of memory. Use a string manipulation solution instead.
Addendum
You didn't specify, but if by some chance these strings came from a database table, I would just add that the appropriate course of action would be to properly normalize it into another table with one row per id rather than store them as a delimited string.
Try with explode and in_array
Example:
$string = "21,22,23,26,";
$string_numbers = explode(",", $string);
$find = 2;
if (in_array($find, $string_numbers)) {
echo "Found";
} else {
echo "Not Found";
}
You can use preg_match if you want to avoid arrays.
$string = "21,22,23,26,";
$find = '2';
$pattern = "/(^$find,|,$find,|,$find$)/";
if (0 === preg_match($pattern, $string)) {
echo "Not Found";
} else {
echo "Found";
}
This will find your id at beginning, middle or at the end of the string. Of course, I am assuming $string does not contain characters other than numbers and commas (like spaces).

Categories