PHP remove ', ' from string if doesn't exist - php

I am running this code:
$stmt = $pdo_conn->prepare("SELECT * from admin where support_emails = :support_emails and logged = :logged and disabled = :disabled ");
$stmt->execute(array(':support_emails' => 'Y', ':logged' => 'in', ':disabled' => ''));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($records) > 0) {
foreach($records as $records2) {
if(filter_var($records2["email"], FILTER_VALIDATE_EMAIL)) {
$SupportEmailList = $records2["email"].', '.$SupportEmailList;
}
if(!empty($SupportEmailList)) {
$SupportEmailList = substr($SupportEmailList, 0, -2); // removes last 2 characters (`, `) from end of string
}
}
}
which returns
email1#domain1.com, email2#domain2.com
when i run in SQL
i have added:
if(!empty($SupportEmailList)) {
$SupportEmailList = substr($SupportEmailList, 0, -2); // removes last 2 characters (`, `) from end of string
}
to remove the ', ' from the end of the string if the last result doesn't exist, but it seems to be creating the following:
email1#domain1.com, email2#domain2.c
rather than:
email1#domain1.com, email2#domain2.com

I would suggest keeping your results in an array and use implode (or join) to join them with a comma.
This way you don't have to deal with trailing comma issue.
$email_address = array();
foreach($records as $records2) {
if(filter_var($records2["email"], FILTER_VALIDATE_EMAIL)) {
array_push($email_address, $records2["email"]);
}
}
$comma_separated_email_address = implode(",", $email_address);
echo $comma_separated_email_address ;

Try trim(). You can pass a list of characters as a second parameter to choose what you want to trim from the beginning/end of the string:
$example_1 = 'email1#domain1.com, email2#domain2.com';
$example_2 = 'email1#domain1.com, email2#domain2.com, ';
$example_1 = trim($example_1, ', ');
$example_2 = trim($example_2, ', ');
var_dump($example_1); // string(38) "email1#domain1.com, email2#domain2.com"
var_dump($example_2); // string(38) "email1#domain1.com, email2#domain2.com"
var_dump(explode(', ', $example_1));
// array(2) { [0]=> string(18) "email1#domain1.com" [1]=> string(18) "email2#domain2.com" }

You could split your string with explode and implode again
$data = explode(',', $elements);
$cleanedData = implode(',', $data);
You could trim space in your data trimming all values in $data array
for ($i = 0; $i < count($data); $i++)
$data[$i] = trim($data[$i]);

I don't understand your question, remove ',' if it doesn't exist? anyway You should fetch your data using PDO::FETCH_NUM. This way you'll get an array of emails like ['email1#domail.com', 'email2#mail.com'] and then if you whant something like 'email1#domail.com, email2#mail.com' use implode to join the elements with a String.

Do it:
$emails = " email1#domain1.com , fsdfsdffdsffds , email2#domain2.com,sddsfsdsd ";
$emails = array_map('trim',explode(',',$emails));
$out = array_map(function($email){
return (filter_var($email, FILTER_VALIDATE_EMAIL)) ? $email : null;
},$emails);
$emails = implode(',',array_filter($out));
print_r($emails);
// email1#domain1.com,email2#domain2.com

Related

how to split string and add additional strin to it

i have a string and i need to add some html tag at certain index of the string.
$comment_text = 'neethu and Dilnaz Patel  check this'
Array ( [start_index_key] => 0 [string_length] => 6 )
Array ( [start_index_key] => 11 [string_length] => 12 )
i need to split at start index key with long mentioned in string_length
expected final output is
$formattedText = '<span>#neethu</span> and <span>#Dilnaz Patel</span>  check this'
what should i do?
This is a very strict method that will break at the first change.
Do you have control over the creation of the string? If so, you can create a string with placeholders and fill the values.
Even though you can do this with regex:
$pattern = '/(.+[^ ])\s+and (.+[^ ])\s+check this/i';
$string = 'neehu and Dilnaz Patel check this';
$replace = preg_replace($pattern, '<b>#$\1</b> and <b>#$\2</b> check this', $string);
But this is still a very rigid solution.
If you can try creating a string with placeholders for the names. this will be much easier to manage and change in the future.
<?php
function my_replace($string,$array_break)
{
$break_open = array();
$break_close = array();
$start = 0;
foreach($array_break as $key => $val)
{
// for tag <span>
if($key % 2 == 0)
{
$start = $val;
$break_open[] = $val;
}
else
{
// for tag </span>
$break_close[] = $start + $val;
}
}
$result = array();
for($i=0;$i<strlen($string);$i++)
{
$current_char = $string[$i];
if(in_array($i,$break_open))
{
$result[] = "<span>".$current_char;
}
else if(in_array($i,$break_close))
{
$result[] = $current_char."</span>";
}
else
{
$result[] = $current_char;
}
}
return implode("",$result);
}
$comment_text = 'neethu and Dilnaz Patel check this';
$my_result = my_replace($comment_text,array(0,6,11,12));
var_dump($my_result);
Explaination:
Create array parameter with: The even index (0,2,4,6,8,...) would be start_index_key and The odd index (1,3,5,7,9,...) would be string_length
read every break point , and store it in $break_open and $break_close
create array $result for result.
Loop your string, add , add or dont add spann with break_point
Result:
string '<span>neethu </span>and <span>Dilnaz Patel </span> check this' (length=61)

Remove duplicate substring from comma seperated string in php

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

Parsing a string separated by semicolon

How can I parse this string
name:john;phone:12345;website:www.23.com;
into becoming like this
$name = "john";
$phone = "12345"
.....
because I want to save the parameter in one table column, I see joomla using this method to save the menu/article parameter.
Something like this(explode() is the way):
$string = 'name:john;phone:12345;website:www.23.com';
$array = explode(';',$string);
foreach($array as $a){
if(!empty($a)){
$variables = explode(':',$a);
$$variables[0] = $variables[1];
}
}
echo $name;
Working example
Please note: String must be like this, variable_name:value;variable_name2:value and the variable_name or variable cant contain ; or :
Here's how I'd do it:
Use explode() and split the string with ; as the delimiter.
Loop through the result array and explode() by :
Store the second part in a variable and push it into the result array
Optionally, if you want to convert the result array back into a string, you can use implode()
Code:
$str = 'name:john;phone:12345;website:www.23.com;';
$parts = explode(';', $str);
foreach ($parts as $part) {
if(isset($part) && $part != '') {
list($item, $value) = explode(':', $part);
$result[] = $value;
}
}
Output:
Array
(
[0] => john
[1] => 12345
[2] => www.23.com
)
Now, to get these values into variables, you can simply do:
$name = $result[0];
$phone = $result[1];
$website = $result[2];
Demo!
Use explode()
explode — Split a string by string
Description
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.
<?php
$string = "name:john;phone:12345;website:www.23.com;";
$pieces = explode(";", $string);
var_dump($pieces);
?>
Output
array(4) {
[0]=>
string(9) "name:john"
[1]=>
string(11) "phone:12345"
[2]=>
string(18) "website:www.23.com"
[3]=>
string(0) ""
}
DEMO
try this
<?php
$str = "name:john;phone:12345;website:www.23.com";
$array=explode(";",$str);
if(count($array)!=0)
{
foreach($array as $value)
{
$data=explode(":",$value);
echo $data[0]." = ".$data[1];
echo "<br>";
}
}
?>

trimming a string in php

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
}

String to array without explode

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

Categories