Get last word with preg_match

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
henriksw
New php-forum User
New php-forum User
Posts: 5
Joined: Tue Jun 05, 2018 10:52 pm

Tue Jun 05, 2018 10:58 pm

I using the code below to get the words between - which works fine except for the last word (Word 4). The string $str is build up correct. I get an empty $part4 variable, can anybody tell me what is wrong? $part1 - $part3 are correct.

<?php
$str1 = "Word1";
$str2 = "Word2";
$str3 = "Word3";
$str4 = "Word4";

$str = $str1 . "-" . $str2 . "-" . $str3 . "-" . $str4;

if (preg_match('/(.*?)-(.*?)-(.*?)-(.*?)/', $str, $match) == 1) {
$part1 = $match[1];
$part2 = $match[2];
$part3 = $match[3];
$part4 = $match[4];
}
?>

AdoptiveSolution
New php-forum User
New php-forum User
Posts: 167
Joined: Wed Jun 15, 2016 8:35 am

Tue Jun 05, 2018 11:40 pm

This gives the result you want

Code: Select all

if (preg_match('/(.*)-(.*)-(.*)-(.*)/', $str, $match) == 1) {
$part1 = $match[1];
$part2 = $match[2];
$part3 = $match[3];
$part4 = $match[4];
}
echo '<pre>';
print_r($match);
echo '</pre>';
?>
Unless there's a reason to use preg_match, why not use explode()?

Code: Select all

<?php
$match = explode('-', $str);
$part1 = $match[0];
$part2 = $match[1];
$part3 = $match[2];
$part4 = $match[3];
echo '<pre>';
print_r($match);
echo '</pre>';
?>

henriksw
New php-forum User
New php-forum User
Posts: 5
Joined: Tue Jun 05, 2018 10:52 pm

Wed Jun 06, 2018 12:48 am

Did'nt thought about the explode function. Great solution, works perfect. Thanks!
AdoptiveSolution wrote:
Tue Jun 05, 2018 11:40 pm
This gives the result you want

Code: Select all

if (preg_match('/(.*)-(.*)-(.*)-(.*)/', $str, $match) == 1) {
$part1 = $match[1];
$part2 = $match[2];
$part3 = $match[3];
$part4 = $match[4];
}
echo '<pre>';
print_r($match);
echo '</pre>';
?>
Unless there's a reason to use preg_match, why not use explode()?

Code: Select all

<?php
$match = explode('-', $str);
$part1 = $match[0];
$part2 = $match[1];
$part3 = $match[2];
$part4 = $match[3];
echo '<pre>';
print_r($match);
echo '</pre>';
?>

Post Reply