PHP preg_replace a pattern multiple times in the same string [duplicate] - php

This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
Regular expression to stop at first match
(9 answers)
Closed 2 years ago.
I have a text string in which I'd like to replace a pattern that occurs multiple times with a tag, like this:
<?php
$str = 'A *word* is a *word*, and this is another *word*.';
preg_replace('/\*([^$]+)\*/', '<b>$1</b>', $str);
?>
However, the function is replacing the whole range from the first asterisk to the last asterisk, i.e. it doesn't separately enclose each pattern with the tag, which is what I'm trying to accomplish.

Try making the pattern lazy:
$str = 'A *word* is a *word*, and this is another *word*.';
$out = preg_replace('/\*([^$]+?)\*/', '<b>$1</b>', $str);
echo $out; // ^^ change here
This prints:
A <b>word</b> is a <b>word</b>, and this is another <b>word</b>.
For an explanation of the minor change to your regex, the updated pattern says to:
\* match *
([^$]+?) followed by any character which is NOT $, one or more times,
until reaching the
\* FIRST closing *

Related

preg_match_all not ignoring characters after pattern [duplicate]

This question already has answers here:
Regular Expression Word Boundary and Special Characters
(3 answers)
Regular expression to stop at first match
(9 answers)
Closed 2 years ago.
If my string is
<?php $str = 'hello world!'; function func_hello($str) { echo $str; }
I want to find the name of any functions in the string
I'm using the code
preg_match_all('%func_.* ?\(%', $c, $matches);
This is a basic example of what I'm doing. In the real world I'm getting results like this
func_check_error($ajax_action_check, array(
func_post('folder') == '/' || func_post(
func_check_error($fvar_ajax_action_check, array(
Whereas I want the result to be
func_check_error(
func_post(
func_check_error(
I've tried \b to set a boundary but it's not working. i.e.
preg_match_all('%\bfunc_.* ?\(\b%', $c, $matches);
The .* capture the opening parenthesis, and then the first parenthesis (after the function name) is captured, because there is the following parenthesis (the one of the array) which correspond to the \( of your pattern.
You should try a more restrictive condition on the function name, such as alphanumeric only or anything but a parenthesis, maybe replace the func_.* by func_[^(]* wich will stop at the first parenthesis match
Simple regex should work fine:
~func_.*\(~
If this is not giving the results you expect, it may be due to another issue with your code and how you're using the regex.

regex to only match a full set of two-part pattern (kinda non-greedy) [duplicate]

This question already has answers here:
Non-greedy string regular expression matching
(2 answers)
Regex lazy quantifier behave greedy
(2 answers)
Closed 3 years ago.
I use preg_match_all to get all matches of a two-part pattern as:
/<(.*?)>[:|\s]+{(.*?)}/
In a string like:
<First>: something <second>: {Second} something <Third>: {Third}
I want to match:
<second>: {Second}
instead of:
<First>: something <second>: {Second}
Working Example
Where did I do wrong?
Use limited repeated set instead of lazy repetition inside the brackets:
<([^>]*)>[:\s]+{(.*?)}
The change is to replace <(.*?)> with <([^>]*)>. The initial version matches the first < then takes lazily any character until it finds :{Second}. If you restrict repetition, regex engine will try to start with <First>, but when it doesn't find :{...} after that, it'll try with the next <
Demo

how to select a substring that starts with x and ends with y through multilines and replace it [duplicate]

This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
Closed 4 years ago.
I want to find a regex that selects a specific string that is defined by it's beginning & ending characters, through multilines, to be replaced by empty string. suppose that I have the following string for example:
I want to select every string that begins with -- and ends with ;
$str = 'some text --text_to_be_replaced; and another text -- text
to
be
replaced; and some text...;';
what I've tried:
$str = preg_replace('/--(.*);/s', '', $str);
but the returned result is: some text while the expected result is some text and another text and some text...;
Your regex is too greedy, try this one:
/--([^;]*);/s
Demo

preg_replace on the actual match ( index 1) instead of whole string [duplicate]

This question already has answers here:
My regex is matching too much. How do I make it stop? [duplicate]
(5 answers)
What do 'lazy' and 'greedy' mean in the context of regular expressions?
(13 answers)
Closed 4 years ago.
Consider
preg_replace('/(lets go).*/', "going", "lets go somewhere")
It will output: "going", I want "going somewhere".
preg_replace seems to replace using the first match which is the whole string "lets go somewhere". How can I make it ignore index 0 and only target index 1?
I don't know what you want to match with .*. You don't need it. This will work fine:
preg_replace('/(lets go)/', "going", "lets go somewhere");
Or you can use a lazy match:
preg_replace('/(lets go).*?/', "going", "lets go somewhere");
Explanation: Your original expression was greedy. That roughly means that .* matches as many characters as possible. .*? is lazy; it matches the minimum amount of characters.
You can also match 'somewhere' as a sub-pattern, and us it in the replacement:
preg_replace('/(lets go)(.*)/', "going\$2", "lets go somewhere");
Here. $0 is "lets go somewhere", $1 is "lets go", $2 is " somewhere". The backslash is needed because "going\$2" is inside double quotes.

What is the regular expression I should use in preg_replace() to find tabs inside all quoted strings and replace with a single space? [duplicate]

This question already has answers here:
How do I replace tabs with spaces within variables in PHP?
(9 answers)
Replace all occurences of char inside quotes on PHP
(5 answers)
Closed 5 years ago.
I know what needs to be done, but have been unsuccessful with the correct regex.
What is the regular expression I should use in preg_replace() to find tabs inside all quoted strings and replace with a single space?
any help would be much appreciated.
Example:
$string = '"Foo\tMan\tChoo"'
preg_replace($expression_string, ' ',$string);
echo $string;//desired result---->'"Foo Man Choo"'
I think this question is not a duplicate
answer : you will need to repeat preg_replace as many time as the max of \t you expect in a field (never could be bothered comming up with a more generic solution : it is usually possible to use this one)
also make sure every line ends with a tab (otherwise the last field will not be processed)
then you need to repeat replacement starting with the max possible number of \t (2 in the example)
$string = '"Foo'."\t".'Man'."\t".'Choo"'."\t".'boo'."\t".'"Foo'."\t".'Man"'."\t";
$string = preg_replace('/"([^"]*)'."\t".'([^"]*)'."\t".'([^"]*)"'."\t".'/','"$1_$2_$3"'."\t",$string);
$string = preg_replace('/"([^"]*)'."\t".'([^"]*)"'."\t".'/','"$1_$2"'."\t",$string);
echo $string;

Categories