How to convert space or newline in textarea to a comma-separated array

I am trying to get the result as a, b, c, d for my array any format in the textarea field is added

$mydomain = htmlspecialchars($_POST['domainlist']);
$domainlist = preg_replace('/\s+/', '', $mydomain);
$domainlist = preg_replace('#\s+#',',',trim($str));
$domainlist = explode(',', $mydomain);


$keyword = $_POST["keyword"]; 
foreach($domainlist as $domain) {
    $file = file_get_contents('http://' . $domain);
    $searchnum = $keyword ; 

    if (stripos($file, $searchnum) !== false) { 
        echo 'record found on '   .$domain. '<br/>';
    } 
    else {
        echo 'record not found ' .$domain.  ' <br/>';
    }
}

for example (pay attention to additional free space)

user adds

a,b  , c, d

or

a     b     c     d

or 

a

b

c

d

everything will lead to

a,b,c,d

which removes an extra space, converts a new line to a comma, or converts a space to a comma and removes extra space

any idea?

+4
source share
2 answers

Since it seems that you want the array to be iterated over, you can split into the characters you want with preg_split, and with the help PREG_SPLIT_NO_EMPTYany additional functions will be eliminated. Then there is no need for explode:

$domainlist = preg_split('/[ ,\n\r]/', $mydomain, null, PREG_SPLIT_NO_EMPTY);
+3

str_replace char. preg_replace, .

$mydomain = htmlspecialchars($_POST['domainlist']);
$domainlist = preg_replace(['/[\s]+/','/[\n]+/'], ",", $mydomain);

$domainlist = explode(',', $mydomain);

: http://sandbox.onlinephpfunctions.com/code/af212f55156ee5770a62adc4c5c70ae820e9c2df

0

Source: https://habr.com/ru/post/1688634/


All Articles