PHP - Remove Certain Strings From Array
Hello guys,
need some help. Let us say i have an array = 2011 ipad 2011 ipad review 2011 ipad price 2011 ipad design 2011 ipad reviews review 2011 ipad 2011 ipad feature I would like to review all the array elements that contain "review"...So the final array should look like 2011 ipad 2011 ipad price 2011 ipad design 2011 ipad feature Thanks Similar TutorialsThis topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=316055.0 Hi all,
I am using foreach statement to gather records and program levenshtein to detect any misspellings and suggesting the correct words.
The thing is i am unable to convert all those strings into a single array.
After trying to correct this issue so many times, i wonder if it is really possible to convert strings into a single array?
Any input is welcome
Hi - I am passing $_POST data from an HTML form. The POST array looks like this: Code: [Select] Array ( [location] => Array ( [0] => Collingwood [1] => Varsity ) [4] => 01 Apr 2012 [1] => 12 Apr 2012 [2] => 01 May 2012 [3] => 01 Jun 2014 [8] => 01 Jul 2012 [6] => 12 Aug 2012 [7] => 20 Apr 2013 [5] => 20 Apr 2014 [submit] => Save Changes ) I am using a foreach loop to separate the keys from the values. The $values include dates and locations. I then pass $values to strtotime to convert the dates to a Unix Time stamp. when strtotime sees the Locations - it throws a PHP error "strtotime() expects parameter 1 to be string, array given" so my question is what can I do to separate the Dates from the locations in order to avoid the error ? MANY THANKS to anyone who can give advice on this ! Hi I am trying to search an array that comes from a power shell script, the array of strings that returns is ever changing as it receives variables from the script. Therefore I need to use preg_grep to search for the word "not" I am also using another array which inverts this I then need to compare these new two arrays to the original and separate the results $working and not working into a table. I would be most grateful for any advice/solutions. The preg_grep aren't displaying anything.
<?php
//phpinfo();
ini_set('display_errors', 'On');
error_reporting(0);//E_ALL
echo '<html>
<style>
body
{
font-family:Calibri,Helvetica,sans-serif;
font-size:100%;
}
</style>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
function uploadJS(){
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
var textAreaValue=document.getElementById(\'ServerList\').value;
var trimmedTextAreaValue=textAreaValue.trim();
if(trimmedTextAreaValue!="") {
document.myForm.submit();
} else{
alert("Server List Text Area is Empty");
}
};
var input=document.getElementById(\'fileSelect\').value;
if(input!="") {
document.myForm.submit();
} else{
alert("You have not selected a file, please select one to proceed.");
}
var handleFileSelect = function(e) {
var files = e.target.files;
if(files.length === 1) {
document.forms.myForm.filecsv.value = files[0].name;
}
}
};
</script>
</head>';
#Upload Code
$target = "D:\Web\Upload/";
$target = $target . basename( $_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). "
has been uploaded";
}
else {
}
if ($uploaded_size > 150000)
{ echo "Your file is too large.<br>";
$ok=0;
}
if ($uploaded_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
if (!($uploaded_type=="text/csv")) { echo "<br>";
$ok=0;
}
$target = "upload/"; $target = $target . basename( $_FILES['uploaded']['name']) ; $ok=1; //This is our size condition
if ($uploaded_size > 350000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($uploaded_type =="text/php")
{ echo "No PHP files<br>";
$ok=0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
}
//If everything is ok we try to upload it
else {
if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
} else
{
}
}
#Start of scripts to check Servers in textbox
if(isset($_POST['ServerList']))
{
//$arry=explode( "\r\n", $_POST['ServerList'] );
$txttrim = trim($_POST['ServerList']);
//$textAr = explode("\n", $text);
//$textAr1 = array_filter($text, 'trim'); // remove any extra \r characters left behind
$txtarea = explode("\n",$txttrim);
$txtarea = array_filter($txtarea,'trim');
foreach ($txtarea as $line => $servername)
{
//$line => $servername;
##check if querying itself....
}
echo '<pre>';
$target="D:/Web/Upload/"; $target= $target . basename( $_FILES['uploaded']['name']) ;
$csv = $target;
//$filename= $_FILES['uploaded']['name'];
$output=shell_exec("powershell -Command D:/Web/scripts/PHPfwrules.ps1 $csv < NUL");
echo '<h6>';
print_r($output);
$nomatch=preg_grep('/^not/i',$output);
echo $nomatch;
$match=preg_grep("/not/",$output,PREG_GREP_INVERT);
echo $match;
if ($working1= array_intersect($output,$match))
{
echo"<link rel=stylesheet type=text/css href=style.css>
<table class=results>
<tr>
<th>Server Name</th>
<th>Working</th>
</tr>
<tr>
<td>".$servername."</td>
<td>".$working1."</td>
</tr></table>
";
}
else if ($notworking1= array_intersect($output,$nomatch))
{
echo"<link rel=stylesheet type=text/css href=style.css>
<table class=results>
<tr>
<th>Server Name</th>
<th>Not Working</th>
</tr>
<tr>
<td>".$servername."</td>
<td>".$notworking1."</td>
</tr></table>
";
}
}
echo' <link rel=stylesheet href=dhtmlwindow.css type=text/css />
<link rel=stylesheet type=text/css href=style.css>
<script src=js/dhtmlwindow.js></script>
<hr />
<table class=results>
<tr>
<th>Server Name</th>
<th>Working</th>
<th> Not Working</th>
</tr>
<tr>
<td>'.$servername.'</td>
<td>'.$working1.'</td>
<td>'.$notworking1.'</td>
<td></td>
';
echo '</pre>';
echo '
<h3>Firewall Implementation </h3>
<h4>Please enter the server below, you can only select one server at a time. </h4>
<!--The form-->
<form action="fw2.php" method="post" name="myForm" id="myForm" enctype="multipart/form-data">
<textarea name=ServerList id=ServerList>
</textarea>
<h5>Please select a CSV file.</h5>
<input name="uploaded" type="file" /><br />
<input type="submit" value="Submit" />
<br>
</html> '
;
?>
Is there a built in function to remove empty array values for example: change Array ( [0] => Bob [1] => [2] => Ryan [3] => Jane ) to Array ( [0] => Bob [1] => Ryan [2] => Jane ) Thanks I am trying to write a dirty script that removes duplicate rows from a multidimensional array. I want to be able to edit the function and spit the duplicates out to a CSV file. Here is my test file: $fullArray = array(array('Jim', 'Jones'), array('Pete', 'Pumpkin'), array('Barak', 'Obama'), array('Jason', 'Newstead'), array('Toby', 'Keith'), array('Jim', 'Jones'), array('Jim', 'Nelson')); echo "<h1>Original</h2>"; for($i=0; $i<count($fullArray); $i++) { echo $fullArray[$i][0] . " " . $fullArray[$i][1] . "<br />"; } echo "<h2>Checked</h2>"; $cleanArray = array(); $cay = array(); $nn=0; $dup=0; // Loop the entire input array foreach ($fullArray as $index => $item) { echo "foreach index:$index<br>"; // Start an internal pointer for ($f=0; $f<count($fullArray); $f++) { echo "for $f "; // if the index is lower or the same as the pointer, skip it to cut down on time if ($f > $index) { // if the rows are the same... if($fullArray[$f][0] == $item[0] && $fullArray[$f][1] == $item[1]) { echo "$item[0] DUP<br>"; // remove it from the array $cay = array_push($cleanArray, array($item[0], $item[1])); array_pop($fullArray[5]); $dup++; } else { // not a duplicate echo " not a dup<br>"; } } else { echo "ON THIS ONE<br>"; } } echo "<br><br>"; } echo"<br>$dup duplicates found<br><br>"; print_r($fullArray); echo "<br /><br>"; // print_r($item); print_r($cleanArray); ?> When I spit out the new fullArray variable, it still has an element from the duplicate record. This is what I get for the output of the full array after the duplicate was removed: Quote Array ( => Array ( => Jim [1] => Jones ) [1] => Array ( => Pete [1] => Pumpkin ) [2] => Array ( => Barak [1] => Obama ) [3] => Array ( => Jason [1] => Newstead ) [4] => Array ( => Toby [1] => Keith ) [5] => Array ( => Jim )[/b] [6] => Array ( => Jim [1] => Nelson ) ) So, I am making a system that shows if there are new posts or not. How I have it done is a singular array called "Read" will have all of the IDs of the read posts. It is entered in the database like so: $ID2= $_SESSION['UserID']; $ID2 = mysql_real_escape_string($ID2); $Readornot=mysql_query("SELECT * FROM forum_read WHERE Reader_ID='$ID2'"); $Readornot2=mysql_fetch_array($Readornot); if($ID2==0) { } else { if(empty($Readornot2)) { $Read1= array("Read" => $Get_TopicID); $Read2 = implode('-',$Read1); mysql_query("INSERT INTO forum_read (Reader_ID,`Read`) values ('$ID2','$Read2')") or die(mysql_error()); } else { $cr_topicid=$Readornot2['Read']; if(strpos($cr_topicid,'-')) { $cr_topicid=explode('-',$cr_topicid); if(!in_array($Get_TopicID,$cr_topicid,true)) { $Read0=implode('-',$cr_topicid); $Read1= array("Read" => $Read0, $Get_TopicID); $Read2= implode('-',$Read1); mysql_query("UPDATE forum_read SET`Read`='$Read2' WHERE Reader_ID='$ID2'") or die(mysql_error()); } } else { if($cr_topicid==$Get_TopicID) { } else { $Read1= array("Read" => $cr_topicid, $Get_TopicID); $Read2= implode('-',$Read1); mysql_query("UPDATE forum_read SET`Read`='$Read2' WHERE Reader_ID='$ID2'") or die(mysql_error()); } } } } It all works fine and dandy to the point where if it's in the database an icon will be black and white, and if its not it wont, signifying read or unread. What I need to do, however, is make it so when there is a new post, it takes all of the entries in the database with the topic ID out of the database, and strips the one part. What I thought of at first was to use str_replace to replace "-" . $TopicID . "-" with "-" But of course, that won't work, because the very first entry could be the topic ID, so it would just be $TopicID- and not -$TopicID- in the database. So, how would I go about doing this? guys please help, i have an array(52,51,52) here i want to insert first & last elements into DB, not second one does not follows the series another array (52,52,53) in this case insert first 2 elements into DB since last element does not follow the series. how is this possible? I can't for the life of me understand how to perform this so I need some professional help here. I have a large array that contains some garbage every Nth and Nth + 1 element that needs to go away. array_filter doesn't work with keys but anyhow, i wouldn't know how to design the function. My keys are numeric, starting from 0. The keys I want to remove are part of this sequence: 8, 9, 18, 19, 28, 29 ... Can someone help me design a generic function to remove these keys? function filter_keys($array, $n, $offset) {} $new_array = filter_keys($array, 10, 8 ); I would maybe have to run this function twice, once for 8 offset and once for 9 offset. Just a quick one, new area for me. I have an array which is looped against another array, if the two values from each ever match then an event occurs, if not then something else. If a match does occur i then want to remove the said value from one of the arrays... is this really all i need to do, seems too simple: unset($saved_dont_use[$j]); Hi, I have an array filled with values like this: Code: [Select] string(1) "Acer 1" string(2) "Acer 2" string(3) "Dell 1" string(4) "Dell 2" string(5) "Dell 3" string(6) "Dell 4" string(7) "Acer 3" string(8) "Acer 4" Is there a way to successfully remove all array strings that starts with a given value like "Acer"? I tried with this snippet, does not work: Code: [Select] foreach($array as &$value) { if(preg_match("/^Acer/", $value)) { unset($value); } } Any ideas will be appreciated! Hi guys! i got this code: Code: [Select] <? $x = "abcde"; str_split($x); for ($k=0; $k<=119; $k++){ $ax = array($x[0],$x[1],$x[2],$x[3],$x[4]); shuffle($ax); $text = implode("", $ax) . ""; echo $text; echo "<br />"; } ?> if you test it you see that it is working but giving me allot of duplicates results! there is a way to ignore duplicaes while it is runing? thanx. Doing an API call and want to remove duplicates so I can display the products by brand. Problem I am having now is when I try to display the brands, I am getting duplicate brands. When I display the brands I am getting Nike, Nike, Reebook. When I just want, Nike, Reebok. My Code Code: [Select] <?php $results = array(); //array from API call $results2 = $results['data']; function multi_unique($array) { foreach ($array as $k=>$na) $new[$k] = serialize($na); $uniq = array_unique($new); foreach($uniq as $k=>$ser) $new1[$k] = unserialize($ser); return ($new1); } $results3 = multi_unique($results2); foreach ($results3 as $var) { echo $var['brand']; ?> <br /> <?php } ?> The array Code: [Select] { "errors": [ ], "warnings": [ ], "data": [ { "url": "http://[...]", "image_url": "[...]", "image_thumb_url": "[...]", "keyword": "Red Running Shoes", "description": "Red Running Shoes - Perfect for long jogs!", "category": "Shoes", "price": "59.99", "price_sale": null, "currency": "USD", "merchant": "", "brand": "Nike", "upc": "0944588778", "isbn": null, "sales": 23 }, { "url": "http://[...]", "image_url": "http://[...]", "image_thumb_url": null, "keyword": "Blue Running Shoes", "description": "Blue Running Shoes - Perfect for long jogs!", "category": "Shoes", "price": "59.99", "price_sale": "49.99", "currency": "USD", "merchant": "", "brand": "Nike", "upc": "0944588779", "isbn": null, "sales": 12 } { "url": "http://[...]", "image_url": "http://[...]", "image_thumb_url": null, "keyword": "Black Running Shoes", "description": "Black Running Shoes - Perfect for long jogs!", "category": "Shoes", "price": "59.99", "price_sale": "49.99", "currency": "USD", "merchant": "", "brand": "Reebok", "upc": "0944554779", "isbn": null, "sales": 12 } ], "coupons": [ ], "countryCode": "US", "page": 1, "limit": 10, "totalRecords": 3 } Hello. I am editing a plugin that is grabbing a multidimensional array, then breaking it out into a foreach statement and doing stuff with the resulting data. What I am trying to do is edit the array before it gets to the foreach statement. I want to look and see if there is a key/value combination that exists, and if it does remove that entire subarray, then reform the array and pass it to a new variable. The current variable Code: [Select] $arrSlides returns several subarrays that look like something like this (I remove unimportant variables for the sake of brevity): Code: [Select] Array ( [0] => Array ( [slide_active] => 1 ) [1] => Array ( [slide_active] => 0 ) ) What I want to do is look and see if one of these subarrays contains the key slide_active with a value of 0. If it contains a value of zero, I want to dump the whole subarray altogether, then reform the multidimensional array back into the variable Code: [Select] $arrSlides. I have tried a few array functions but have not had any luck. Any suggestions? Thanks in advance, Jason When I remove 1 session item using this it works fine when I select more than 1 item to be removed I get unexpected results, I have checked the outputted html to see what positions get echoed into the remove check box and they are correct, so I guess the problem lies in my remove code here is the part of the form that sends the remove check box <?php for ($basket_counter=0;$basket_counter<$_SESSION['ses_basket_items'];$basket_counter++) { $price=sprintf("%01.2f",$ses_basket_price[$basket_counter]); $quantity=$ses_basket_amount[$basket_counter]; $code=$ses_basket_stockcode[$basket_counter]; $itemID=$ses_basket_id[$basket_counter]; $name=$ses_basket_name[$basket_counter]; $image=$ses_basket_image[$basket_counter]; $size=$ses_basket_size[$basket_counter]; $sizechoice=$ses_basket_sizechoice[$basket_counter]; // create array from sizes and make the option box selections if ($sizechoice!="" && (!in_array($sizechoice, array('One Size', 'one size', 'free size', 'Free Size', 'Adjustable', 'adjustable')))) { // add size trigger $sizelist="add"; //create the array $sizepick=explode(",", $sizechoice); } else { $sizepick=$sizechoice; } // adjust gst for AU customers if ($country=='AU') { $price=sprintf("%01.2f",($price*1.1)); $unit=sprintf("%01.2f",($price/$quantity)); } else { $unit=sprintf("%01.2f",($price/$quantity)); } ?> <tr> <td align='center' class='rescon' style="border-bottom:solid #330000 1px;"><input type="checkbox" name="remove[<?php echo $basket_counter; ?>]" value="<?php echo $basket_counter; ?>" /></td> and here is the part of the code that processes the removal of the items $remove = $_POST['remove']; if (isset($remove) && ($remove!='')) { foreach($remove AS $key => $remove_position){ array_splice ($ses_basket_name, $remove_position, 1); array_splice ($ses_basket_amount, $remove_position, 1); array_splice ($ses_basket_price, $remove_position, 1); array_splice ($ses_basket_stockcode, $remove_position, 1); array_splice ($ses_basket_image, $remove_position, 1); array_splice ($ses_basket_size, $remove_position, 1); array_splice ($ses_basket_sizechoice, $remove_position, 1); array_splice ($ses_basket_id, $remove_position, 1); $_SESSION['ses_basket_items']--; } } I am using a form with checkboxes named remove[$remove_position] and the positions in the form are correct for each item in the array, but when I select more than 1 item to delete they are not always the correct items only the first 1 selected. What am I doing wrong here?? Hi all, Is there a function or method to delete element from current position in array without knowing the index. For example: $ar = array( 1, 2, 3, "test", 4, 5, "test2" ); while( $v = current( $ar ) ) { if( key( $ar ) == "test" ) { // remove element from the array where key equals "test" // i could count every cycle and splice from that index but i wonder can that be done without it // i am looking at the php array functions but i can't find any that will delete from element from current position in array echo 'key( $ar ) je test. key( $ar ): ' . key( $ar ); } next( $ar ); } One thing that i don't understand is that when i run example above the "test" key is found and when i echo it it gives me 0. Hello I have a while loop which outputs countrys from the database (im making a "filter by" function). For example, the loop outputs: Denmark Belgium Holland Brazil Japan Brazil Denmark I want to sort these alphabetically and then remove duplicates... Can somebody explain to me how? I don't know how to get them into an array to do it... Can anyone let me know what I am doing wrong. I am sure it will (after the fact) be obvious, but I don't see it right now. Wish to remove all array elements which do not implement ValidatorCallbackInterface. Thanks <?php interface ValidatorCallbackInterface{} class ValidatorCallback implements ValidatorCallbackInterface{} function array_filter_recursive($input) { foreach ($input as &$value) { if (is_array($value)) { $value = array_filter_recursive($value); } } return array_filter($input, function($v) { return $v instanceOf ValidatorCallbackInterface; }); } function recursive_unset(&$array) { foreach ($array as $key => $value) { if (is_array($value)) { recursive_unset($value); if(empty($value)) { unset($array[$key]); } } elseif(!$value instanceOf ValidatorCallbackInterface) { unset($array[$key]); } } } $validatorCallback = new ValidatorCallback(); $rules=[ 'callbackId'=>"integer", 'info'=>[ 'arrayofobjects'=>[$validatorCallback], 'foo1'=>'bar1' ], 'foo2'=>'bar2', 'bla'=>[ 'a'=>'aa', 'b'=>'bb', ], 'singleobject'=>$validatorCallback ]; echo('original rules'.PHP_EOL); var_dump($rules); $desiredrules=[ 'info'=>[ 'arrayofobjects'=>[$validatorCallback] ], 'singleobject'=>$validatorCallback ]; echo('desired rules'.PHP_EOL); var_dump($desiredrules); echo('array_filter_recursive'.PHP_EOL); var_dump(array_filter_recursive($rules)); echo('recursive_unset'.PHP_EOL); recursive_unset($rules); var_dump($rules);
original rules array(5) { ["callbackId"]=> string(7) "integer" ["info"]=> array(2) { ["arrayofobjects"]=> array(1) { [0]=> object(ValidatorCallback)#1 (0) { } } ["foo1"]=> string(4) "bar1" } ["foo2"]=> string(4) "bar2" ["bla"]=> array(2) { ["a"]=> string(2) "aa" ["b"]=> string(2) "bb" } ["singleobject"]=> object(ValidatorCallback)#1 (0) { } } desired rules array(2) { ["info"]=> array(1) { ["arrayofobjects"]=> array(1) { [0]=> object(ValidatorCallback)#1 (0) { } } } ["singleobject"]=> object(ValidatorCallback)#1 (0) { } } array_filter_recursive array(1) { ["singleobject"]=> object(ValidatorCallback)#1 (0) { } } recursive_unset array(2) { ["info"]=> array(2) { ["arrayofobjects"]=> array(1) { [0]=> object(ValidatorCallback)#1 (0) { } } ["foo1"]=> string(4) "bar1" } ["singleobject"]=> object(ValidatorCallback)#1 (0) { } }
(1) I need to remove the lowest and higest values from an array. I need to actually remove the two lowest and two highest. I suppose the best thing would be to sort the array and then use a function that just drops the first and last values (twice). Is this the best way? Which function would drop the lowest / highest values? (2) I then need to get the remaining first and last (highest and lowest) values. $array[0] would get first, and revesing the order and $array[0] again would get the last. Is this the best way? |