i'm still quite new to programming, so please excuse me.
I need to do the following:
Right now i have a string being output with two value: one with characters and numbers, a comma and the second with just a boolean value.
9fjrie93, 1
I would like to trim the string so it just ourputs as the boolean value. e.g.
1
I then need to perform an equality check on the boolean value. If it's 1 do one thing, else do something else. Would a simple if statement suffuce?
Thanks very much
No need for explode if it's always the last character.
<?php
$val = '9fjrie93, 1';
if( substr( $val, -1 ) === '1' ) {
// do stuff.
}
else {
// do stuff. Just other stuff.
}
How about:
$vals = explode(", ", "9fjrie93, 1");
if ($vals[1]) ...
You can also use list to name the results returned:
$original_str = '9fjrie93, 1';
list($characters, $boolean) = explode(', ', $original_str);
echo $boolean;
Try this:
$str = '9fjrie93, 1';
$str = explode(', ', $str); //it returns array('9fjrie93', '1')
$str = end($str); //takes the last element of the array
$mystring = '9fjrie93, 1';
$findme = ',';
$pos = strpos($mystring, $findme);
$i= substr($mystring,$pos);
$string = "9fjrie93, 1";
$val = substr($string, (strrpos($string, ',')+1));
Don't use explode since it's slower
If the 1 is always at the end of the line, you can do:
$line = '9fjrie93, 1'
if ( $line[strlen([$line])-1] == '1' ) {
// do stuff
} else {
// do other stuff
}
Which should at least perform better than explode, str_replace and substr solutions.
$pos = strpos($source_str, ',');
substr($source_str, $x_pos + 1);
hope this will solve it.
$output = str_replace(',', '', strstr('9fjrie93, 1', ','));
if( $output == '1' ) {
....do something
} else {
...do something else
}
Related
I have this string: $entitlemnet = '43857403,erot,43857403,erot,rejh'
I want to remove all the duplicate values from this string. How can i do that?
See code below.
$roql_Ent_result = RNCPHP\ROQL::query($EntQuery)->next();
while ($Ent_result = $roql_Ent_result->next())
{
$Entitlement = $Ent_result['Entitlement'];
$findme = $Entitlement.",";
$pos = stripos($EntitlementString, $findme);
if ($pos === false)
{
$EntitlementString = $EntitlementString.$Entitlement.", ";
}
}
if ($EntitlementString != "")
{
$EntitlementString = substr($EntitlementString,0,(strlen($EntitlementString)-2)).";";
}
If you simply want to remove the duplicates from the string.
$entitlemnet = '43857403,erot,43857403,erot,rejh';
$unique_string = implode(',', array_unique(explode(',', $entitlemnet)));
Turn your string into an array by splitting it with explode() by
delimiter ','
Remove duplicate values with the function array_unique()
Turn the array back into a string by concatenating the array values with
delimiter ','
Try this
$entitlemnet = "43857403,erot,43857403,erot,rejh";
$result = implode(',', array_unique(explode(',', $entitlemnet)));
echo $result;
I think you can do it like this:
$entitlemnet = "43857403,erot,43857403,erot,rejh";
$result = implode(',', array_unique(explode(',', $entitlemnet)));
echo $result;
Will result in:
43857403,erot,rejh
I would like to search for a substring in php so that it will be at the end of the given string.
Eg
on string 'abd def' if I search for def it would be at the end, so return true. But if I search for abd it will return false since it is not at the end.
Is it possible?
You could use preg_match for this:
$str = 'abd def';
$result = (preg_match("/def$/", $str) === 1);
var_dump($result);
An alternative way to do it which does not require splitting by a separator or regular expressions. This tests whether the last x characters equal the test string, where x equals the length of the test string:
$string = "abcdef";
$test = "def";
if(substr($string, -(strlen($test))) === $test)
{
/* logic here */
}
Assuming whole words:
$match = 'def';
$words = explode(' ', 'abd def');
if (array_pop($words) == $match) {
...
}
Or using a regex:
if (preg_match('/def$/', 'abd def')) {
...
}
This answer should be fully robust regardless of full words or anything else
$match = 'def';
$words = 'abd def';
$location = strrpos($words, $match); // Find the rightmost location of $match
$matchlength = strlen($match); // How long is $match
/* If the rightmost location + the length of what's being matched
* is equal to the length of what's being searched,
* then it's at the end of the string
*/
if ($location + $matchlength == strlen($words)) {
...
}
Please look strrchr() function. Try like this
$word = 'abcdef';
$niddle = 'def';
if (strrchr($word, $niddle) == $niddle) {
echo 'true';
} else {
echo 'false';
}
I have the following text string: "Gardening,Landscaping,Football,3D Modelling"
I need PHP to pick out the string before the phrase, "Football".
So, no matter the size of the array, the code will always scan for the phrase 'Football' and retrieve the text immediately before it.
Here is my (lame) attempt so far:
$array = "Swimming,Astronomy,Gardening,Rugby,Landscaping,Football,3D Modelling";
$find = "Football";
$string = magicFunction($find, $array);
echo $string; // $string would = 'Landscaping'
Any help with this would be greatly appreciated.
Many thanks
$terms = explode(',', $array);
$index = array_search('Football', $terms);
$indexBefore = $index - 1;
if (!isset($terms[$indexBefore])) {
trigger_error('No element BEFORE');
} else {
echo $terms[$indexBefore];
}
//PHP 5.4
echo explode(',Football', $array)[0]
//PHP 5.3-
list($string) = explode(',Football', $array);
echo $string;
$array = array("Swimming","Astronomy","Gardening","Rugby","Landscaping","Football","3D" "Modelling");
$find = "Football";
$string = getFromOffset($find, $array);
echo $string; // $string would = 'Landscaping'
function getFromOffset($find, $array, $offset = -1)
{
$id = array_search($find, $array);
if (!$id)
return $find.' not found';
if (isset($array[$id + $offset]))
return $array[$id + $offset];
return $find.' is first in array';
}
You can also set the offset to be different from 1 previous.
I have a string which may or may not contain commas. If it does, I want it exploded into an array; if it doesn't, I still want the string saved to the new identifier. My code clearly doesn't work. Anyone have any better ideas?
if(explode(",", $_SESSION['shoparea']))
{
$areas = explode(",", $_SESSION['shoparea']);
} else {
$areas = $_SESSION['shoparea'];
}
What is the correct syntax for this operation?
if(strpos($_SESSION['shoparea'], ',') !== false) {
$areas = explode(',', $_SESSION['shoparea']);
} else {
$areas = $_SESSION['shoparea'];
}
Everything can be exploded, if there are no instances of the delimiter it becomes a singleton array, so it may be simpler to do
$result = explode(",", $_SESSION['shoparea']);
if (count($result) == 1)
$areas = $result[0];
else
$areas = $result;
You could use http://php.net/strpos function to ensure that ',' are present.
you could do this for examle
$areas = $_SESSION['shoparea'];
if(strpos($areas, ',') !== false) {
$areas = explode(",", $areas);
}
All you need is
$_SESSION['shoparea'] = "xx"; // Test value ..
if (!$areas = explode(",", $_SESSION['shoparea'])) {
$areas = array($_SESSION['shoparea']);
}
Output
array
0 => string 'xx' (length=2)
Note : $areas needs to always be array .. if you are using a loop you might have issue so i converted it ..
if (substr_count($_SESSION['shoparea'], ',') > 0) {
$areas = explode(",", $_SESSION['shoparea']);
}
else {
$areas = $_SESSION['shoparea'];
}
I am using an api to retrieve data from another server the data returned is something like this:
accountid=10110 type=prem servertime=1263752255 validuntil=1266163393
username= curfiles=11 curspace=188374868 bodkb=5000000 premkbleft=24875313
This is a whole string I need two values out of whole string, I am currently using preg_match to get it, but just to learn more and improve my coding is there any other way or function in which all values are automatically convert to array?
Thank You.
Sooo, my faster-than-preg_split, strpos-based function looks like this:
function unpack_server_data($serverData)
{
$output = array();
$keyStart = 0;
$keepParsing = true;
do
{
$keyEnd = strpos($serverData, '=', $keyStart);
$valueStart = $keyEnd + 1;
$valueEnd = strpos($serverData, ' ', $valueStart);
if($valueEnd === false)
{
$valueEnd = strlen($serverData);
$keepParsing = false;
}
$key = substr($serverData, $keyStart, $keyEnd - $keyStart);
$value = substr($serverData, $valueStart, $valueEnd - $valueStart);
$output[$key] = $value;
$keyStart = $valueEnd + 1;
}
while($keepParsing);
return $output;
}
It looks for an equals character, then looks for a space character, and uses these two to decide where a key name begins, and when a value name begins.
Using explode is the fastest for this, no matter what.
However, to answer you question, you can do this many ways. But just because you can, doesn't mean you should. But if you really wanna make it weird, try this.
UPdated using strpos
$arr = array();
$begin = 0;
$str = trim($str); # remove leading and trailing whitespace
while ($end = strpos($str, ' ', $begin)) {
$split = strpos($str, '=', $begin);
if ($split > $end) break;
$arr[substr($str, $begin, $split-$begin)] = substr($str, $split+1, $end-$split-1);
$begin = $end+1;
}
try out parse_str maybe you need to do str_replace(' ', '&', $string); before