How to Explode and Trim Whitespace

Explode string on commas and trim potential spaces from each value

You can do the following using array_map:

$new_arr = array_map('trim', explode(',', $str));

Explode and Trim in one line with PHP

Use preg_split().

list($host, $dbname, $username, $password) = preg_split("/\\s*\\n\\s*/",trim($config));

how to remove whitespace from explode

A combination of array_map and array_filter, or possibly just array_filter, will do the trick.

array_map with trim will remove extra whitespaces:

$imeitransferserial = array_map('trim',$imeitransferserial );

array_filter will remove empty elements from the array:

$imeitransferserial = array_filter($imeitransferserial);

If you can have a value of 0 in the array, you will want to use strlen as a callback for array_filter:

$imeitransferserial = array_filter($imeitransferserial, 'strlen');

By default, array_filter will remove anything that evaluates to 0.

PHP explode line break and strip blank lines and white spaces

Try this...

Input

 $data = "        Object One

Object Two

Object Three

Object Four
Object Five

Object Six";

Solution

$result = array_filter(array_map('trim',explode("\n", $data)));
echo "<pre>"; print_r($result);

Output

Array
(
[0] => Object One
[3] => Object Two
[6] => Object Three
[8] => Object Four
[9] => Object Five
[11] => Object Six
)

Remove spaces from values in the array explode() returns

Use trim() to remove whitespace before inserting

foreach ($friendarray as $friend) 
{
$query .= "('" . $id . "','" . trim($friend) . "'),";
}

Explode Comma Separated Values with or without Spaces

You have to try the below code:

$myString = "one, two, three";
$myArray = explode(',', $myString);
$trimmed_myArray = array_map('trim',$myArray);
print_r($trimmed_myArray);

How to explode and keep white space in strings?

You will not be able to differentiate between spaces within country names and spaces as country delimiters.

You could modify your input array and use explode():

$state_list='United Kingdom,Spain,Russia,Saudi Arabia';

foreach(explode(',',$state_list) as $state){
echo $state,"<br>";
}

Explode string on second last and last space to create exactly 3 elements

You can approach this using explode and str_replace

$string = "Testing (3WIR)";
$stringToArray = explode(":",str_replace("(",":(",$string));
echo '<pre>';
print_r($stringToArray);

Edited question answer:-

$subject = "Fluency in English Conversation Defklmno (1WIR)";
$toArray = explode(' ',$subject);
if(count($toArray) > 2){
$first = implode(" ",array_slice($toArray, 0,count($toArray)-2));
$second = $toArray[count($toArray)-2];
$third = $toArray[count($toArray)-1];
$result = array_values(array_filter([$first, $second, $third]));
}else{
$result = array_values(array_filter(explode(":",str_replace("(",":(",$subject))));
}

DEMO HERE



Related Topics



Leave a reply



Submit