Php's Preg_Match() and Preg_Match_All() Functions

PHP's preg_match() and preg_match_all() functions

preg_match stops looking after the first match. preg_match_all, on the other hand, continues to look until it finishes processing the entire string. Once match is found, it uses the remainder of the string to try and apply another match.

http://php.net/manual/en/function.preg-match-all.php

Get all matches using regexp preg_match() function in PHP

Use preg_match_all instead of preg_match.

PHP: Use preg_match_all to create objects and call object functions

As stated in the comments; what you are probably after is preg_replace_callback. Here is an example of its usage with your problem:

function getBandCampMarkup($matches){
$bc = new BandcampAction($matches[1], $matches[2]);
return $bc->player();
}

$data = preg_replace_callback("/\[bandcamp=(.+?)\](.+?)\[\/bandcamp\]/", "getBandCampMarkup", $data);
echo $data;

This is of course assuming the $bc->player() returns a string of the output. If this function just echos the data then you can can use ob_start and ob_get_clean to capture the output as a string as so:

ob_start();
$bc->player();
return ob_get_clean();

PHP preg_match function not working as expected

There are several issues with your code.

  1. If you're using single quotes for the pattern and want to match a literal backslash, you need to use at least \\\ or even \\\\ to produce an escaped backslash \\. Just echo your pattern if unsure.

  2. Instead of using the global flag g which is not available in PHP use preg_match_all. If it matches, it returns the number of matches. You can check match condition by preg_match_all(...) > 0

  3. Unsure about ^ in [\\^]. if you don't need it, drop it. Further [0-9] can be reduced to \d. Also I would add a word boundary \b after \d{4} if something like \u12345 should not be matched.

See this PHP demo at tio.run

$pattern = '/\\\u\d{4}\b/i';
# echo $pattern;

if(preg_match_all($pattern, $data['title'], $matches, PREG_OFFSET_CAPTURE) > 0){
print_r($matches[0]);
} else{
echo "Not Found";
}

Php preg_match_all, wordpress function

The code you found on the internet is kind of irrelevant. In order to achieve what you want you need something like this:

$str = "[image name=ubuntustudio-tribal-54] ";
$pat = "~\[image name=([^\]]+)~i";
preg_match($pat, $str, $matches);
$name = $matches[1];

After that $name would be bound to ubuntustudio-tribal-54.

See the docs for more details regarding PHP's preg_match.

See also, this great source of info about Regular Expressions in general.



Related Topics



Leave a reply



Submit