PHP string function in getting a specific line of a string in array string value PHP string function in getting a specific line of a string in array string value codeigniter codeigniter

PHP string function in getting a specific line of a string in array string value


$val = '(Avelino Curato)avelinocurato@gmail.com';$email = ltrim(strstr($val, ')'), ')');echo $email; // avelinocurato@gmail.com

[[ DEMO ]]

For the 2nd example you would not use strtok() as you want to get what is after the parentheses, so you would use strstr() to get the parentheses and anything after it, then you chop off the parentheses from the string.

If you want to be creative you can do this:

$val = '(Avelino Curato)avelinocurato@gmail.com';//$val = 'avelinocurato@gmail.com(Avelino Curato)';$email = strip_tags(strtr($val, '()', '<>'));echo $email; // avelinocurato@gmail.com

[[ DEMO ]]

This will work in both cases, and does not require PHP to use the regex engine. It basically converts the opening and closing parentheses to opening and closing angle brackets which would then be considered a HTML tag, and then running strip tags will remove that portion. Simple, quick and easy to understand.


Try this code.

$val = array(    '0' => '(Avelino Curato)avelinocurato@gmail.com',    '1' => '(Ferdinand Balbin)ferdinand@apploma.com',    '2' => 'ferdinand@apploma.com(Ferdinand Balbin)');array_walk($val, function(&$value) { /* Use array walk to loop trough the array */    $matches = array(); //create array to preserve matches after preg_match    preg_match('/[A-Za-z0-9_-]+@[A-Za-z0-9_-]+\.([A-Za-z0-9_-][A-Za-z0-9_]+)/', $value, $matches);     $value = $matches[0]; //set the [0] match in value});print_r($val);


Try my little example

function try_explode(){    $store_array = array();    $val = array(        '0' => 'avelinocurato@gmail.com(Avelino Curato)',        '1' => 'ferdinand2apploma.com(Ferdinand Balbin)'    );    foreach ($val as $key => $value) {        $names[$key] = preg_replace("/.*\(([^\)]+)\)$/is", "\$1", $value);        $emails[$key] = preg_replace("/^([^\(]+).*/is", "\$1", $value);        $store_array[$key] = "(".$names[$key].") ".$emails[$key];    }    var_dump($names);    var_dump($emails);    var_dump($store_array);}