-1

What is the best way to capture a string between 2 certain characters in PHP? Looking online some people say to explode it, some suggest using str_ functions, some suggest regex,

:>Test!1.221ddba.0_31df0888d4d13e9456a2bdafc93437ff@~127.0.0.1 JOIN UUNN :%#Test

I wish to capture the string between the : and the !, i.e. >Test. How can I do this with a regex, or is there a simpler way?

user316478
  • 59
  • 5

2 Answers2

0

here is the PHP with RegEx. Maybe it helps :)

$re = '/(?<=:).*(?=!)/';
$str = ':>Test!1.221ddba.0_31df0888d4d13e9456a2bdafc93437ff@~127.0.0.1 JOIN UUNN :%#Test';
preg_match($re, $str, $matches, PREG_OFFSET_CAPTURE, 0);
// Print the entire match result
var_dump($matches);

Link to Regex101.com

0

After some modifying the answers that i already found I came up with this RegEx

/(?<=:)[^:!]*(?=!)/miu

Regex explanation:

(?<=:) - Positive lookbehind ensuring what precedes matches : literally
[^:!]* - Matches any character except : and ! any number of times.
(?=!) - Positive lookahead ensuring what follows is ! literally.

A bit basic explanation

The above regex actually not only grabs every symbol between : and !, but also ensures, that between these two sybols there are no other occurenses of either : or !.
Actuall, it only maches text that is strictly between : and !. Everything else is not matched. If there is no : followed by a ! at all then the result will be empty.

This was tested using https://regex101.com/.

Php code generated for the test is

<?php
$re = '/(?<=:)[^:!]*(?=!)/m';
$str = ':ssuguwuug!jsgejjgjj!yhjyt:feeeeeg!uuuuuuu:uuuuu:uuu!';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the first match result, since it looks like OP only wanted a first match 
var_dump($matches[0]);

?>

EDIT

I really tried to make it as un-Greedy as I could, but * is a Greedy Quantifier