Good day!
I would like some help in removing strings inside the square brackets and including the square brackets.
The string looks like this:
$string = "Lorem ipsum dolor<br /> [ Context are found on www.example.com ] <br />some text here. Text here. [test] Lorem ipsum dolor.";
I just would like to remove the brackets and its contents that contain "www.example.com". I would like to retain "[test]"
in the string and any other brackets have no "www.example.com"
in them.
Thanks!
Note: The OP has dramatically changed the question. This solution was designed to handle the question in its original (more difficult) form (before the "www.example.com" constraint was added.) Although the following solution has been modified to handle this additional constraint, a simpler solution would now probably suffice (i.e. anubhava's answer).
Here is my tested solution:
Note that the regex skips removal of bracketed material from within: HTML comments, CDATA sections, SCRIPT and STYLE elements and from within HTML tag attribute values. Given the following XHTML markup (which tests these scenarios), the above function correctly removes only the bracketed contents within html element contents:
Here is the same markup after being run through the PHP function above:
This solution should work quite well for just about any valid (X)HTML you can throw at it. (But please, no funky shorttags or SGML comments!)
The below code will change
<br/>
to newline characters:Output:
The simplest method I can think of is using a regular expression to math everything between
[
and]
then replace it with""
. The code below will replace the string you used in the example. If the actual strings that need to be removed are more complex you can change the regular expression to match then. I recommend using regexpal.com for testing your regular expressions.$string = preg_replace("\[[A-Za-z .]*\]","",$string);
Use a regular expression something like
/\[.*?\]/
. The backslashes are necessary, otherwise it will try to match any single character.
,*
, or?
instead.OUTPUT
PS: It will work with line broken in multiple lines.