I am trying to pass a php variable as a delimiter to explode(). The variable's value is being fetched from an html form.

form:

<select name="delimiter">
<option value="\t">Tab Space</option>
<option value=",">Comma (,)</option>
<option value=";">Semi colon (;)</option>
<option value="&">Ampersand (&)</option>
<option value="|">Pipe (|)</option>
</select>

php:

$delimiter=$_POST['delimiter'];
$arr=explode($delimiter, $line);

Above doesn't seem to work. It does not recognize the delimiter and hence gives me a single element in $arr i.e. same as $line. Any suggestions would be greatly appreciated. Thank you

有帮助吗?

解决方案

why don`t you use preg_split for this.. for example

<select name="delimiter">
<option value="\t">Tab Space</option>
<option value=",">Comma (,)</option>
<option value=";">Semi colon (;)</option>
<option value="&">Ampersand (&)</option>
<option value="\|">Pipe (|)</option>
</select>

and php script

$delimiter =  $_POST['delimiter'];

$arr =  preg_split("/".$delimiter."/", $line);    

其他提示

Your problem has to be the way that your $line is setup.
This works for me:

$string = "hello\tworld\tthis\tis\tfun";

$options = ["\t"=>'tab', ','=>'comma', ';'=>'semi-colon', '&'=>'amperstand','|'=>'pipe'];

echo "<form method=\"post\">";
echo "<select name=\"delimList\">\r\n";
foreach($options as $val => $option){
    echo "<option value=\"$val\">$option</option>\r\n";
}
echo "</select>\r\n";
echo "<input type=submit></form>";
if(isset($_POST['delimList'])){
    $delim = $_POST['delimList'];
    $array = explode($delim, $string);
    print_r($array);
}

Closest I got to a solution is the following line in php:

$delimiter =  $_POST['delimiter'];

eval("\$delimiter = \"$delimiter\";");

Initially, $delimiter is created string(2) after eval becomes string(1) tab in php.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top