How do I replace the square bracket and its contents in php.
For example I would like to output something like
// 'Hello World Today Hello Everybody Anybody'
when I echo $txt.
$txt = 'Hello World [this-echo] Hello Everybody [nobody]';
That's a simple search and replace for your defined markers.
$text = 'Hello World [this-echo] Hello Everybody [nobody]';
$markers=array('[this-echo]','[nobody]');
$replacements=array('Today','Anybody');
$text= str_replace($markers,$replacements,$text);
Output
Hello World Today Hello Everybody Anybody
Fiddle
When the content of the brackets is not defined somewhere you can get them with preg_match_all:
$string = 'This is a [test]';
preg_match_all('/\[([^\]*]+?)\]/', $string, $matches);
The regex will match everything between the opening bracket and the closing bracket and put the results in the matches array.
The matches array for the example:
Array(2) {
[0]=>
array(1) {
[0]=>
string(6) "[test]"
}
[1]=>
Array(1) {
[0]=>
string(4) "test"
}
}
Now you can replace [test] with something you want and have the content between the brackets available.
Doing it by Regex is one way to achieve your text replacement:
$txt = 'Hello World [this-echo] Hello Everybody [nobody]';
$replaced_text = preg_replace('/(\\[[^\\]]*\\])/i', '<TEXTTOREPLACE>', $txt);
echo $replaced_text;
Explanation of the regular expression (/regex/options):
With:
/(\[[^\]]*\])/i
you are matching everything from [, all chars except ] to the closing ] ignoring the case with the i at the end of the pattern.
Ignoring the case (uppercase, lowercase):
/regex/i
Related
I am trying to find a solution on how to remove everything outside specific value in brackets, including the value in brackets.
This is what I mean. I have this string
$str = "[:de]Some german text[:en]Some English text[:]";
What I want to achieve to get the text between [:de]and[:en] and to remove everything else, so the result has to be
$str = "Some german text";
I guess it should be some preg_match or some regex solution, but all I found was, how to remove the text in between, but not to keep the text in between and remove everything else.
Any ideas are welcome.
I guess,
(?<=\[:de\]).*?(?=\[:en\])
might work OK here.
Test
$re = '/(?<=\[:de\]).*?(?=\[:en\])/s';
$str = '[:de]Some german text 1[:en]Some English text[:] [:de]Some german text 2[:en]Some English text[:]
[:de]Some german text 3[:en]Some English text[:]';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
Output
array(3) {
[0]=>
array(1) {
[0]=>
string(18) "Some german text 1"
}
[1]=>
array(1) {
[0]=>
string(18) "Some german text 2"
}
[2]=>
array(1) {
[0]=>
string(18) "Some german text 3"
}
}
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
RegEx Circuit
jex.im visualizes regular expressions:
Thanks to Emma's answer this is what I came up as a solution.
$re = '/(?<=\[:de\]).*?(?=\[:en\])/s';
$result = preg_match($re, $str, $match);
$result = $match[0];
This question already has answers here:
Reference - What does this regex mean?
(1 answer)
Where does the case insensitive modifier go in this regular expression
(3 answers)
Closed 3 years ago.
I have a simple regex code to match a whole line in text file that has a specific word. I use PHP function preg_match_all.
this is my regex pattern:
$word= 'world';
$contents = '
this is my WoRld
this is my world
this is my wORLD
this is my home
';
$pattern = "/^.*$word.*\$/m";
preg_match_all($pattern, $contents, $matches);
// results will be in $matches[0]
this function get the full line but search for case sensitive only so it will return the second line only of the text.
I want it to match all line (that has "world" word in any form).
I read about using /i but I don't know how to combine it with the pattern above.
I tried:
/^.$pattern.\$/m/i
/^.$pattern.\$/m/i
/^.$pattern.\$/i
This expression,
(?i)^.*\bworld\b.*$
might simply return those desired strings.
Test
$re = '/(?i)^.*\bworld\b.*$/m';
$str = 'this is my WoRld
this is my world
this is my wORLD
this is my home';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
Output
array(3) {
[0]=>
array(1) {
[0]=>
string(16) "this is my WoRld"
}
[1]=>
array(1) {
[0]=>
string(16) "this is my world"
}
[2]=>
array(1) {
[0]=>
string(16) "this is my wORLD"
}
}
RegEx Circuit
jex.im visualizes regular expressions:
I have the string: This is a [[bla]] and i want a [[burp]] and i need to put in an array the 2 string [[bla]] and [[burp]].
The regexp i am trying to use is:
$pattern = "/\[\[.+\]\]/"
The problem is that the output is: [[bla]] and [[burp]] ,because i suppose it take the first [[ with the last ]]
How can i fix the pattern?
Make it ungreedy, see it on Regexr
/\[\[.+?\]\]/
or use a negated character class, see it on Regexr
/\[\[[^\]]+\]\]/
You need ungreedy repitition (lazy) matching here -> *? to get only the text between [[ ]] and not between [[ ]] [[ ]]:
$pattern = "/\[\[(.*?)\]\]/"
Also you need a matching group to get only the text between the square brackets and not the brackets itself -> (.*?)
Example:
$string = "This is a [[bla]] and i want a [[burp]]";
$pattern = "/\[\[(.*?)\]\]/";
preg_match_all($pattern , $string, $matches);
var_dump($matches[1]);
Output:
array(2) {
[0]=>
string(3) "bla"
[1]=>
string(4) "burp"
}
i'm wondering what kind of regex I could use to essentially extract all the words that have a dash infront of them in a given string. I'm going to be using it to allow users to omit certain words from the search results of my website.
For example, say I have
$str = "this is a search -test1 -test2";
I'm trying to have it save "test1" and "test2" to an array because they have a dash right infront.
Could anyone help me out
Use the following pattern /\-(\w+)/. Example:
$string = 'this is a search -test1 -test2';
$pattern = '/\-(\w+)/';
if(preg_match_all($pattern, $string, $matches)) {
$result = $matches[1];
}
var_dump($result);
Output:
array(2) {
[0] =>
string(5) "test1"
[1] =>
string(5) "test2"
}
Explanation:
/.../ delimiter chars
\- a dash (must be escaped as it has a special meaning in the regex language
(...) special capture group. stores the content between them in $matches[1]
\w+ At least one ore more word characters
this do the job:
<pre><?php
$string = 'Phileas Fog, Passe-Partout -time -day -#StrAn-_gE+*$Word²²²';
preg_match_all('~ -\K\S++~', $string, $results);
print_r($result);
I have for example such string - "7-th Road" or "7th number some other words" or "Some word 8-th word".
I need to get the first occurrence of number and all other next symbols to first occurrence of space.
So for examples above i need such values "7-th", "7th", "8-th".
And then from these matches like "7-th" i need extract only numbers in other operations.
Thanks in advance!
Regex should be /(\d+)([^\d]+)\s/ and the numbers would resolve to $1 and the ending characters to $2
Sample Code:
$string = '7-th Road';
preg_match_all('/(\d+)([^\d]+)\s/', $string, $result, PREG_PATTERN_ORDER);
var_dump($result[1]);
array(1) {
[0]=> string(1) "7"
}
var_dump($result[2]);
array(1) {
[0]=> string(1) "-th"
}
Are you asking for something like this?
#(\d+)-?(?:st|nd|rd|th)#
Example
If you would like to get just nums from the text use it:
preg_match_all('/(\d+)[th|\-th]*?/','7-th", "7th", "8-th', $matches);
But if you would like to remove 'th' or other just do replacement:
preg_replace('/(\d+)[th|\-th]*?/','$1', 'some string')
Not sure about the last one...