1000Gbps
1000Gbps

Reputation: 1517

How to extract all words in a string with preg_match before a specific character

Say we have the following string:

Terminator1 Terminator2 Terminator3: Terminator4

And the given regex which only saves Terminator3

(\w+)(?=:)

How I must save the first 3 Terminators in a string, because the php's preg_match offers to save results only as array? I'm thinking to use implode() as the only option for gluing all words ...

Example result:

var_dump($terminators);
array(3) {
  [0]=>
  string(11) "Terminator1"
  [1]=>
  string(11) "Terminator2"
  [2]=>
  string(11) "Terminator3"
}

Thanks in advance

Upvotes: 0

Views: 1013

Answers (3)

mickmackusa
mickmackusa

Reputation: 47903

I don't think I'd use regex for this task (unless you have a special requirement) because there are faster single-function non-regex methods available.

Code: (Demo)

$input='Terminator1 Terminator2 Terminator3: Terminator4';
//$input='Terminator1 Terminator2 Terminator3 Terminator4'; // no delimiter

echo "strstr: ";
var_export(strstr($input,':',true));  // false when no delimiter is found
echo "\n\n";

echo "strtok: ";
var_export(strtok($input,':'));  // fullstring when no delimiter is found
echo "\n\n";

echo "explode: ";
var_export(explode(':',$input,2)[0]);  // fullstring when no delimiter is found
echo "\n\n";

echo "preg_replace: ";
var_export(preg_replace('/:.*/','',$input));  // fullstring when no delimiter is found
echo "\n\n";

echo "preg_match: ";
var_export(preg_match('/[^:]*/',$input,$out)?$out[0]:'error');  // fullstring when no delimiter is found
echo "\n\n";

echo "preg_split: ";
var_export(preg_split('/:.*/',$input)[0]);  // fullstring when no delimiter is found

Output:

strstr: 'Terminator1 Terminator2 Terminator3'

strtok: 'Terminator1 Terminator2 Terminator3'

explode: 'Terminator1 Terminator2 Terminator3'

preg_replace: 'Terminator1 Terminator2 Terminator3'

preg_match: 'Terminator1 Terminator2 Terminator3'

preg_split: 'Terminator1 Terminator2 Terminator3'

Upvotes: 1

user557597
user557597

Reputation:

Do it in 2 steps,

  1. Match [^:]+(?=:)
  2. Explode the result on whitespace.

All done!

Upvotes: 1

$string = "Terminator1 Terminator2 Terminator3: Terminator4";

$result = strtok($string, ":");

echo $result;

Upvotes: 1

Related Questions