I have a string stored in a variable, this string may appear in the next ways:
$sec_ugs_exp = ''; //Empty one
$sec_ugs_exp = '190'; //Containing the number I want to delete (190)
$sec_ugs_exp = '16'; //Containing only a number, not the one Im looking for
$sec_ugs_exp = '12,159,190'; // Containing my number at the end (or in beginning too)
$sec_ugs_exp = '15,190,145,86'; // Containing my number somewhere in the middle
I need to delete the 190 number if it exists and deleting also the comma attached after it unless my number is at the end or it is alone(there is no commas in that case)
So in the examples I wrote before, I need to get a return like this:
$sec_ugs_exp = '';
$sec_ugs_exp = '';
$sec_ugs_exp = '16';
$sec_ugs_exp = '12,159';
$sec_ugs_exp = '15,145,86';
Hope I explained myself, sorry about my English. I tried using preg_replace and some other ways, but I always failed in detecting the comma.
My final attempt not using regex:
$codes = array_flip(explode(",", $sec_ugs_exp));
unset($codes[190]);
$sec_ugs_exp = implode(',', array_keys($codes));
A simple regex should do the trick: /(190,?)/:
$newString = preg_replace('/(190,?)/', '', $string);
Demo: http://codepad.viper-7.com/TIW9D6
Or if you want to prevent matches like:
$sec_ugs_exp = '15,1901,86';
^^^
You could use:
(190(,|$))
Quick and dirty, but should work for you:
str_replace(array(",190","190,","190"), "", $sec_ugs_exp);
Note the order in the array is important.
$array = explode ( ',' , $sec_ugs_exp );
foreach ( $array AS $key => $number )
{
if ( $number == 190 )
{
unset($array[$key]);
}
}
$sec_ugs_exp = implode ( ',' , $array );
This will work if a number if 1903 or 9190
None of the answers here account for numbers beginning or ending with 190.
$newString = trim(str_replace(',,', ',', preg_replace('/\b190\b/', '', $string)), ',');
try
str_replace('190,', '', $sec_ugs_exp);
str_replace('190', '', $sec_ugs_exp);
or
str_replace('190', '', $sec_ugs_exp);
str_replace(',,' ',', $sec_ugs_exp);
if there are no extra spaces in your string
Related
I have a problem - hope you can help.
My users will enter a string like this:
'dt', 'time_hour', 'loc', 'protocol_category', 'service_identifier', 'mcc', 'imsi', 'service_dl_bytes', 'service_ul_ bytes'
Depending on their other inputs, I then remove two fields from this list (for example, service_identifier and service_dl_bytes)
This leaves lots of stray commas in the string.
I need some logic that says:
- there can only be one consecutive comma
- there should not be a comma as the last character
- comma, space comma is also not permitted
Basically, the format has to be 'input', 'input2', 'input3'
Can anyone help me .. i tried with the below, but it doesn't work in all use cases
elseif ($df3aggrequired == "YES" and $df3agg2required == "NO" ) {
#remove spaces from select statement
$df3group0v2 = str_replace($df3aggfield, '', $df3select);
#replace aggfield1 with null
$df3group1v2 = str_replace(' ', '', $df3group0v2);
#replace instances of ,, with ,
$df3group3v2 = preg_replace('/,,+/', ',', $df3group1v2);
$finalstring0df3v2 = rtrim($df3group3v2, ',');
$finalstring1df3v2 = str_replace('\'\'', '', $finalstring0df3v2);
$finalstringdf3v2 = str_replace('.,', '', $finalstring1df3v2);
$finalstringdf31v2 = str_replace(',,', ',', $finalstringdf3v2);
$finalcleanup = preg_replace('/,,+/', ',', $finalstringdf31v2);
echo"\\<br> .groupBy(";
echo "$finalcleanup";
echo ")";
I also think that string replacements can cause issues, so went for a similar process to geoidesic, this code tries to stick with the fields being a CSV list, and removes the quotes round them as part of the decoding, but also puts them back again in the result.
$fields = "'dt', 'time_hour', 'loc', 'protocol_category', 'service_identifier', 'mcc', 'imsi', 'service_dl_bytes', 'service_ul_ bytes'";
$removeFields = true ;
$fieldList = str_getcsv($fields, ",", "'");
if ( $removeFields == true ) {
if ( ($key = array_search('loc', $fieldList)) !== false ) {
unset ( $fieldList[$key] );
}
$fields = "'".implode("', '", $fieldList)."'";
}
echo $fields;
The example removes the 'loc' field, but this can be modified to remove any fields required.
The final output is (assuming 'loc' is removed)...
'dt', 'time_hour', 'protocol_category', 'service_identifier', 'mcc', 'imsi', 'service_dl_bytes', 'service_ul_ bytes'
Whatever your string after removing process is, you may want to run a single preg_replace over it using a positive lookahead:
^\s*(,\s*)*|,\s*(?=,|$)
Live demo
Breakdown:
^\s*(,\s*)* Match unwanted commas at beginning
| Or
,\s*(?=,|$) Match consecutive commas or trailing ones
PHP code:
$string = preg_replace('~^\s*(,\s*)*|,\s*(?=,|$)~', '', $string);
You'd better consider removing unwanted commas while removing words.
If it is a comma-separated list, then don't use str_replace. Turn the string into an array first by splitting it on the commas:
$myArray = explode(',' $myString);
Then remove the parts of the array you don't want and make it a string again:
$fieldsToDelete = ["service_identifier", "service_dl_bytes"];
$newArray = [];
foreach($myArray as $key => $value) {
if(!in_array($value, $fieldsToDelete) {
array_push($newArray, $value)
}
}
$newString = implode(',', $newArray)
The following code works on the index of the fields you want to remove.
Works the same as the answer written by #geoidesic but uses index of field in string instead of a string match.
$user_input = "'dt', 'time_hour', 'loc', 'protocol_category', 'service_identifier', 'mcc', 'imsi', 'service_dl_bytes', 'service_ul_ bytes'";
$input_array = explode(',', $user_input);
// 4 = 'service_indentifier'
// 8 = 'service_ul_ bytes'
$remove_input = array(4, 8);
foreach($remove_input as $array_index) {
unset($input_array[$array_index]);
}
$parsed_input = implode(',', $input_array);
var_dump($parsed_input);
// Output: string(80) "'dt', 'time_hour', 'loc', 'protocol_category', 'mcc', 'imsi', 'service_dl_bytes'"
You have try with
$var = preg_replace(["/'[\s,]*,[\s,]*'/", "/^[\s,]*|[\s,]*$/"], ["', '", ""], $var);
It can help!
Suppose I have a string:
$str="1,3,6,4,0,5";
Now user inputs 3.
I want that to remove 3 from the above string such that above string should become:
$str_mod="1,6,4,0,5";
Is there any function to do the above?
You can split it up, remove the one you want then whack it back together:
$str = "1,3,6,4,0,5";
$userInput = 3;
$bits = explode(',', $str);
$result = array_diff($bits, array($userInput));
echo implode(',', $result); // 1,6,4,0,5
Bonus: Make $userInput an array at the definition to take multiple values out.
preg_replace('/\d[\D*]/','','1,2,3,4,5,6');
in place of \d just place your digit php
If you don't want to do string manipulations, you can split the string into multiple pieces, remove the ones you don't need, and join the components back:
$numberToDelete = 3;
$arr = explode(',',$string);
while(($idx = array_search($numberToDelete, $components)) !== false) {
unset($components[$idx]);
}
$string = implode(',', $components);
The above code will remove all occurrences of 3, if you want only the first one yo be removed you can replace the while by an if.
I've got this string, but I need to remove specific things out of it...
Original String: hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64.
The string I need: sh-290-92.ch-215-84.lg-280-64.
I need to remove hr-165-34. and hd-180-1.
!
EDIT: Ahh ive hit a snag!
the string always changes, so the bits i need to remove like "hr-165-34." always change, it will always be "hr-SOMETHING-SOMETHING."
So the methods im using wont work!
Thanks
Depends on why you want to remove exactly those Substrigs...
If you always want to remove exactly those substrings, you can use str_replace
If you always want to remove the characters at the same position, you can use substr
If you always want to remove substrings between two dots, that match certain criteria, you can use preg_replace
$str = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
$new_str = str_replace(array('hr-165-34.', 'hd-180-1.'), '', $str);
Info on str_replace.
The easiest and quickest way of doing this is to use str_replace
$ostr = "hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64";
$nstr = str_replace("hr-165-34.","",$ostr);
$nstr = str_replace("hd-180-1.","",$nstr);
<?php
$string = 'hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64';
// define all strings to delete is easier by using an array
$delete_substrings = array('hr-165-34.', 'hd-180-1.');
$string = str_replace($delete_substrings, '', $string);
assert('$string == "sh-290-92.ch-215-84.lg-280-64" /* Expected result: string = "sh-290-92.ch-215-84.lg-280-64" */');
?>
Ive figured it out!
$figure = $q['figure']; // hr-165-34.sh-290-92.ch-215-84.hd-180-1.lg-280-64
$s = $figure;
$matches = array();
$t = preg_match('/hr(.*?)\./s', $s, $matches);
$s = $figure;
$matches2 = array();
$t = preg_match('/hd(.*?)\./s', $s, $matches2);
$s = $figure;
$matches3 = array();
$t = preg_match('/ea(.*?)\./s', $s, $matches3);
$str = $figure;
$new_str = str_replace(array($matches[0], $matches2[0], $matches3[0]), '', $str);
echo($new_str);
Thanks guys!
I've gone through this address:
Passing an array to a query using a WHERE clause
and found that if I use a join clause to separate values , is also at the end of the array. How can I remove last?
I am using like this
$ttst=array();
$ttst=array();
$tt = "SELECT frd_id FROM network WHERE mem_id='$userId'";
$appLdone = execute_query($tt, true, "select");
foreach($appLdone as $kk=>$applist){
$ttst[] = $applist['frd_id'];
}
$result = implode(',', $ttst);
then also coming last ,
Thanks.
but it doesn't give single quote to each value .
join(',', array_filter($galleries))
array_filter gets rid of empty elements that you seem to have. Of course, you should take care not to have empty elements in there in the first place.
You could use trim() (or rtrim()):
$myStr = 'planes,trains,automobiles,';
$myStr = trim($myStr, ',');
$str = "orange,banana,apple,";
$str = rtrim($str,',');
This will result in
$str = "orange,banana,apple";
Update
Based on your situation:
$result = implode(',', $ttst);
$result = rtrim($result,',');
$arr = array(...);
$last = end($arr);
unset($last);
If the trailing "," is an array element of itself, use array_pop(), else, use rtrim()
$array = array('one','two',3,',');
array_pop($array);
print_r($array);
Gives:
Array ( [0] => one 1 => two 2 => 3
)
No need for length. Just take from beginning to the (last character - 1)
$finalResult = $str = substr($result, 0, -1);
Use implode() instead! See Example #1 here http://php.net/manual/en/function.implode.php
Edit:
I think a quick fix would be (broken down in steps):
$temp = rtrim(implode(',', $ttst), ','); //trim last comma caused by last empty value
$temp2 = "'"; //starting quote
$temp2 .= str_replace(",", "','", $temp); //quotes around commas
$temp2 .= "'"; //ending quote
$result = $temp2; // = 'apples','bananas','oranges'
This should give you single-quote around the strings, but note that if some more values in the array are sometimes empty you will probably have to write a foreach loop and build the string.
I'm currently using str_replace to remove a usrID and the 'comma' immediately after it:
For example:
$usrID = 23;
$string = "22,23,24,25";
$receivers = str_replace($usrID.",", '', $string); //Would output: "22,24,25"
However, I've noticed that if:
$usrID = 25; //or the Last Number in the $string
It does not work, because there is not a trailing 'comma' after the '25'
Is there a better way I can be removing a specific number from the string?
Thanks.
YOu could explode the string into an array :
$list = explode(',', $string);
var_dump($list);
Which will give you :
array
0 => string '22' (length=2)
1 => string '23' (length=2)
2 => string '24' (length=2)
3 => string '25' (length=2)
Then, do whatever you want on that array ; like remove the entry you don't want anymore :
foreach ($list as $key => $value) {
if ($value == $usrID) {
unset($list[$key]);
}
}
var_dump($list);
Which gives you :
array
0 => string '22' (length=2)
2 => string '24' (length=2)
3 => string '25' (length=2)
And, finally, put the pieces back together :
$new_string = implode(',', $list);
var_dump($new_string);
And you get what you wanted :
string '22,24,25' (length=8)
Maybe not as "simple" as a regex ; but the day you'll need to do more with your elements (or the day your elements are more complicated than just plain numbers), that'll still work :-)
EDIT : and if you want to remove "empty" values, like when there are two comma, you just have to modifiy the condition, a bit like this :
foreach ($list as $key => $value) {
if ($value == $usrID || trim($value)==='') {
unset($list[$key]);
}
}
ie, exclude the $values that are empty. The "trim" is used so $string = "22,23, ,24,25"; can also be dealt with, btw.
Another issue is if you have a user 5 and try to remove them, you'd turn 15 into 1, 25 into 2, etc. So you'd have to check for a comma on both sides.
If you want to have a delimited string like that, I'd put a comma on both ends of both the search and the list, though it'd be inefficient if it gets very long.
An example would be:
$receivers = substr(str_replace(','.$usrID.',', ',', ','.$string.','),1,-1);
An option similar to Pascal's, although I think a bit simipler:
$usrID = 23;
$string = "22,23,24,25";
$list = explode(',', $string);
$foundKey = array_search($usrID, $list);
if ($foundKey !== false) {
// the user id has been found, so remove it and implode the string
unset($list[$foundKey]);
$receivers = implode(',', $list);
} else {
// the user id was not found, so the original string is complete
$receivers = $string;
}
Basically, convert the string into an array, find the user ID, if it exists, unset it and then implode the array again.
I would go the simple way: add commas around your list, replace ",23," with a single comma then remove extra commas. Fast and simple.
$usrID = 23;
$string = "22,23,24,25";
$receivers = trim(str_replace(",$usrID,", ',', ",$string,"), ',');
With that said, manipulating values in a comma separated list is usually sign of a bad design. Those values should be in an array instead.
Try using preg:
<?php
$string = "22,23,24,25";
$usrID = '23';
$pattern = '/\b' . $usrID . '\b,?/i';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
?>
Update: changed $pattern = '/$usrID,?/i'; to $pattern = '/' . $usrID . ',?/i';
Update2: changed $pattern = '/' . $usrID . ',?/i to $pattern = '/\b' . $usrID . '\b,?/i' to address onnodb's comment...
Simple way (providing all 2 digit numbers):
$string = str_replace($userId, ',', $string);
$string = str_replace(',,','', $string);