how to Remove nbsp element from an array - php

i have elements in my php array who contain &nbsp elements , i try to remove the elements who contain only space (&nbsp), so i apply on my array:
$steps = array_map( 'html_entity_decode', $steps);
$steps = array_map('trim',$steps);
$steps = array_filter($steps, 'strlen'); //(i try also array_filter($steps);
but the elements reside.
Any idea please

Try this:
/**
* Function to strip away a given string
**/
function remove_nbsp($string){
$string_to_remove = " ";
return str_replace($string_to_remove, "", $string);
}
# Example data array
$steps = array("<p>step1</p>", "<p>step2</p>", "<p>step3</p>", "<p> </p>", " ", "<p> </p>", "<p>step4</p>");
$steps = array_map("strip_tags", $steps);
//Strip_tags() will remove the HTML tags
$steps = array_map("remove_nbsp", $steps);
//Our custom function will remove the character
$steps = array_filter($steps);
//Array_filter() will remove any blank array values
var_dump($steps);
/**
* Output:
array(4) {
[0]=>
string(5) "step1"
[1]=>
string(5) "step2"
[2]=>
string(5) "step3"
[6]=>
string(5) "step4"
}
*/
You might even find it easier to do a foreach():
foreach($steps as $dirty_step){
if(!$clean_step = trim(str_replace(" ", "", strip_tags($dirty_step)))){
//Ignore empty steps
continue;
}
$clean_steps[] = $clean_step;
}

Related

php function for rading out values from string

i want to make a php loop that puts the values from a string in 2 different variables.
I am a beginner. the numbers are always the same like "3":"6" but the length and the amount of numbers (always even). it can also be "23":"673",4:6.
You can strip characters other than numbers and delimiters, and then do explode to get an array of values.
$string = '"23":"673",4:6';
$string = preg_replace('/[^\d\:\,]/', '', $string);
$pairs = explode(',', $string);
$pairs_array = [];
foreach ($pairs as $pair) {
$pairs_array[] = explode(':', $pair);
}
var_dump($pairs_array);
This gives you:
array(2) {
[0]=>
array(2) {
[0]=>
string(2) "23"
[1]=>
string(3) "673"
}
[1]=>
array(2) {
[0]=>
string(1) "4"
[1]=>
string(1) "6"
}
}
<?php
$string = '"23":"673",4:6';
//Remove quotes from string
$string = str_replace('"','',$string);
//Split sring via comma (,)
$splited_number_list = explode(',',$string);
//Loop first list
foreach($splited_number_list as $numbers){
//Split numbers via colon
$splited_numbers = explode(':',$numbers);
//Numbers in to variable
$number1 = $splited_numbers[0];
$number2 = $splited_numbers[1];
echo $number1." - ".$number2 . "<br>";
}
?>

PHP: Check if array key is specific string

I'm trying to create an if statement. based on the string of the
$var = "Apple : Banana";
$array = explode(":", $var);
print_r($array); //array([0] => 'Apple' [1] => 'Banana')
if ($array[1] == "Banana") {
echo "Banana!";
}
The string has space before and after :, so array will be
array(2) {
[0]=> string(6) "Apple "
[1]=> string(7) " Banana"
}
You need to remove space from items using trim() and then compare it.
$var = "Apple : Banana";
$array = explode(":", $var);
if (trim($array[1]) == "Banana") {
echo "Banana!";
}
Your condition doesn't work because each element of array has space. You should remove excess spaces. You can use trim function to remove spaces and array_map function to apply trim in each element of the array.
For example:
$var = "Apple : Banana";
$array = array_map('trim', explode(":", $var));
if ($array[1] == "Banana") {
echo "Banana!";
}
result:
Banana!
You can do it by using preg_split and regex
$parts = preg_split('/\s+\:\s+/', $var);
Then on $parts you will get:
array(2) { [0]=> string(5) "Apple" [1]=> string(6) "Banana" }

Create Arrays From Numbered List From a String

I have a plain string like this:
1 //here is a number defines phrase name
09/25/2013 //here is a date
<i>some text goes here</i> //and goes text
2
09/24/2013
text goes on and on
4 //as you can see, the numbers can skip another
09/23/2013
heya i'm a text
I need to create array from this but the numbers that defines phrases must give me the date of that line and return the text when i called it. Like,
$line[4][date] should give me "09/23/2013"
Is that possible, if possible can you explain me how to do this?
$stringExample = "1
09/25/2013
<i>some text goes here</i>
2
09/24/2013
text goes on and on
and on and on
4
09/23/2013
heya i'm a text";
$data = explode("\r\n\r\n", $stringExample);
$line = array();
foreach ($data as $block) {
list($id, $date, $text) = explode("\n", $block, 3);
$index = (int) $id;
$line[$index] = array();
$line[$index]["date"] = trim($date);
$line[$index]["text"] = trim($text);
}
var_dump($line) should output:
array(3) {
[1]=>
array(2) {
["date"]=>
string(10) "09/25/2013"
["text"]=>
string(26) "<i>some text goes here</i>"
}
[2]=>
array(2) {
["date"]=>
string(10) "09/24/2013"
["text"]=>
string(34) "text goes on and on
and on and on"
}
[4]=>
array(2) {
["date"]=>
string(10) "09/23/2013"
["text"]=>
string(15) "heya i'm a text"
}
}
You can test it here.
If the structure of the file is a coerent pattern of rows, with PHP you read each line and each 1st you have the number, each 2nd you have the date, each 3rd you have the text, each 4th you have empty, you reset the counter to 1 and go on like that, and put values in arrays, using even an external index, or the 1st line (number) as index.
try this:
EDIT: should now work for multi line text.
//convert the string into an array at newline.
$str_array = explode("\n", $str);
//remove empty lines.
foreach ($str_array as $key => $val) {
if ($val == "") {
unset($str_array[$key]);
}
}
$str_array = array_values($str_array);
$parsed_array = array();
$count = count($str_array);
$in_block = false;
$block_num = 0;
$date_pattern = "%[\d]{2}/[\d]{2}/[\d]{2,4}%";
for ($i = 0; $i < $count; $i++) {
//start the block at first numeric value.
if (isset($str_array[$i])
&& is_numeric(trim($str_array[$i]))) {
// make sure it's followed by a date value
if (isset($str_array[$i + 1])
&& preg_match($date_pattern, trim($str_array[$i + 1]))) {
//number, followed by date, block confirmed.
$in_block = true;
$block_num = $i;
$parsed_array[$str_array[$i]]["date"] = $str_array[$i + 1];
$parsed_array[$str_array[$i]]['text'] = "";
$i = $i + 2;
}
}
//once a block has been found, everything that
//is not "number followed by date" will be appended to the current block's text.
if ($in_block && isset($str_array[$i])) {
$parsed_array[$str_array[$block_num]]['text'].=$str_array[$i] . "\n";
}
}
var_dump($parsed_array);

Regular expression for utf-8 string sliceing at linebreaks or after a number of characters

I found a function on the web, that uses a regular experssion, to iterate over a string and inserts linebreaks after a specified number of characters, so it will fit into a narrow table cell with a fixed width.
here is the function:
/**
* wordwrap for utf8 encoded strings
*
* #param string $str
* #param integer $len
* #param string $what
* #return string
* #author Milian Wolff <mail#milianw.de>
*/
function utf8_wordwrap($str, $width, $break, $cut = false) {
if (!$cut || $_SESSION['wordwrap']) {
$regexp = '#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){'.$width.'}#';
} else {
return $str; //if no wordwrap turned on, returns the original string
}
if (function_exists('mb_strlen')) {
$str_len = mb_strlen($str,'UTF-8');
} else {
$str_len = preg_match_all('/[\x00-\x7F\xC0-\xFD]/', $str, $var_empty);
}
$while_what = ceil($str_len / $width);
$i = 1;
$return = '';
while ($i < $while_what) {
preg_match($regexp, $str,$matches);
$string = $matches[0];
$return .= $string.$break;
$str = substr($str, strlen($string));
$i++;
}
return $return.$str;
}
here is the regexp:
#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){20}#
It does its job well, if it's combined with a while loop until there is a line break character in the string.
An example string:
1. first
2. second
3. third
The output of prag_match:
array (
0 => '1. first
2. second
3',
)
so it just counts for the 20th character, and returns it.
What I would need is:
To make it return everything until a new line char (\n) OR if there isn't any, return the first 20 char.
So the output in this case would be something like this:
array (
0 => '1. first',
1 => '2. second',
2 => '3. third'
)
UPDATE:
I tried Steve Robbins's answer and it worked perfectly, until the string had some spec UTF-8 characters in it. It's my fault, I didn't provide a decent example in the first place.
Here is what it does:
<?php
header('Content-type: text/html; charset=UTF-8');
$input = '1. first
2. second
3. third
ez eg nyoulőűúúú3456789öüö987654323456789öü
pam
param';
$output = array();
foreach (explode("\n", $input) as $value) {
foreach (str_split($value, 20) as $v) {
$trimmed = trim($v);
if (!empty($trimmed))
$output[] = $trimmed;
}
}
var_dump($output);
And the output is:
array(8) {
[0]=>
string(8) "1. first"
[1]=>
string(9) "2. second"
[2]=>
string(8) "3. third"
[3]=>
string(20) "ez eg nyoulőűúú�"
[4]=>
string(20) "�3456789öüö987654"
[5]=>
string(13) "323456789öü"
[6]=>
string(3) "pam"
[7]=>
string(5) "papam"
}
http://codepad.org/Gt4CshXt
Why use regex?
<?php
$input = '1. first
2. second
3. third';
$output = array();
foreach (explode("\n", $input) as $value) {
foreach (str_split($value, 20) as $v) {
$trimmed = trim($v);
if (!empty($trimmed))
$output[] = $trimmed;
}
}
var_dump($output);
Gives
array(3) {
[0]=>
string(8) "1. first"
[1]=>
string(9) "2. second"
[2]=>
string(8) "3. third"
}
Example: http://codepad.org/OoillEUu
Thanks everyone for your efforts! I've found the solution here
<?php
header('Content-Type: text/html; charset=utf-8');
$input = '1. first
2. second
3. third
ez eg nyoulőűúúú3456789öüö987654323456789öü
pam
papam';
var_dump(utf8_wordwrap($input,20,"<br>",true));
function utf8_wordwrap($string, $width=20, $break="\n", $cut=false)
{
if($cut) {
// Match anything 1 to $width chars long followed by whitespace or EOS,
// otherwise match anything $width chars long
$search = '/(.{1,'.$width.'})(?:\s|$)|(.{'.$width.'})/uS';
$replace = '$1$2'.$break;
} else {
// Anchor the beginning of the pattern with a lookahead
// to avoid crazy backtracking when words are longer than $width
$pattern = '/(?=\s)(.{1,'.$width.'})(?:\s|$)/uS';
$replace = '$1'.$break;
}
return preg_replace($search, $replace, $string);
}
?>
string '1. first
<br>2. second
<br>3. third
<br>ez eg<br>nyoulőűúúú3456789öüö<br>987654323456789öü
<br>pam
<br>papam<br>' (length=122)

split a comma separated string in a pair of 2 using php

I have a string having 128 values in the form of :
1,4,5,6,0,0,1,0,0,5,6,...1,2,3.
I want to pair in the form of :
(1,4),(5,6),(7,8)
so that I can make a for loop for 64 data using PHP.
You can accomplish this in these steps:
Use explode() to turn the string into an array of numbers
Use array_chunk() to form groups of two
Use array_map() to turn each group into a string with brackets
Use join() to glue everything back together.
You can use this delicious one-liner, because everyone loves those:
echo join(',', array_map(function($chunk) {
return sprintf('(%d,%d)', $chunk[0], isset($chunk[1]) ? $chunk[1] : '0');
}, array_chunk(explode(',', $array), 2)));
Demo
If the last chunk is smaller than two items, it will use '0' as the second value.
<?php
$a = 'val1,val2,val3,val4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = array(array_shift($buffer), array_shift($buffer)); }
return $result;
}
$result = x($a);
var_dump($result);
?>
Shows:
array(2) { [0]=> array(2) { [0]=> string(4) "val1" [1]=> string(4) "val2" } [1]=> array(2) { [0]=> string(4) "val3" [1]=> string(4) "val4" } }
If modify it, then it might help you this way:
<?php
$a = '1,2,3,4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = sprintf('(%d,%d)', array_shift($buffer), array_shift($buffer)); }
return implode(',', $result);
}
$result = x($a);
var_dump($result);
?>
Which shows:
string(11) "(1,2),(3,4)"

Categories