如何将字符串转换为多个变量?

问题描述 投票:0回答:3

我想创建一个电子表单,用户可以在textarea字段上输入多个电子邮件地址。

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<br><br>    
 <textarea  name="email"></textarea>
<input type="submit" name="submit" value="Submit">      
</form>    

当用户在textarea上键入多个电子邮件时,如下图所示enter image description here

 <?php    

echo $_POST["name"].'<br>';
echo $_POST["email"].'<br>'; //make the three email convert to three variable.
?>

任何想法这样做???

foreach ($_POST["email"] as $email) {
     // anyidea
    }
 $_POST["email"][0] = '[email protected]';
 $_POST["email"][1] = '[email protected]';
 $_POST["email"][2] = '[email protected]';

非常感谢你 。

php forms textarea
3个回答
3
投票

这就是我要做的,

  $emails = array_filter(array_map('trim', explode(',', $_POST['email'])));

爆炸根据第一个参数array_map将字符串分解为数组,类似于循环,并对每个元素应用修剪,修剪空白区域(从两侧移除空白空间)。数组过滤器删除任何虚假的数组元素。比如''空字符串。

所以这照顾了类似的事情

 [email protected], ,,[email protected]

产量

array(
   '[email protected]',
   '[email protected]'
)

如果你想要真正灵活做到这一点

  $emails = array_filter(array_map('trim', preg_split('/(,|\||\s)/', $_POST['email'])))

其中与上面相同,但允许您使用空格逗号或管道作为分隔符。


1
投票

您可以尝试在模式\s*,\s*上拆分CSV电子邮件列表。这将处理逗号分隔符之前或之后的任何数量的空格。

$input = "[email protected], [email protected] , [email protected]";
$emails = preg_split('/\s*,\s*/', $input);
print_r($emails);

Array ( [0] => [email protected] [1] => [email protected] [2] => [email protected] )

0
投票

您可以在PHP http://php.net/manual/en/function.explode.php中使用explode功能

// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
© www.soinside.com 2019 - 2024. All rights reserved.