Replace exact content or tag - php

I think that to replace exactly one tag, the best is to use preg_replace. I tried str_replace and replaced all characters. For example if I want replace the two PHP tags in <?php print "Hello parents"; ?> by using str_replace I do this :
$char1=array("<?php","?>");
$char_2=array("","");
str_replace($char1,$char2,$content);
The result will be this :
Hello parents
str_replace "replace all chars"
How can I do the same thing with preg_replace? Because I don't understand how to put chars or separators
Here is what I tried :
$content="<?php Hello parents?>"
$chars='/(\<?php),(?>)/i';
$sus="";
echo preg_replace($chars, $sus, $content);

$content="<?php Hello parents?>"
$chars = "/(<\?php|\?>)/i";
$sus="";
echo preg_replace($chars, $sus, $content);
You can use the | separator to say replace <?php or ?>
And the ? character needs to be escaped as within the RegEx it means 0 or 1 occurances

Related

Change ocurrence inside a string

I am needing to change occurrence of string or numbers in php. In this situation, I need to change this, if it happens:
[code:154545edppy]
// my code here
[/code]
to this
[code]
// my code here
[/code]
I need to verify if letters and strings appear inside de opening block code. I am trying to do this with str_replace, but it's not working.
my code now:
$text = "[code:54as] [/code]";
$text = str_replace("[code: {(\d)}{(\w)}]", "[code]", $text);
$text = str_replace("[/code: {(\d)}{(\w)}]", "[/code]", $text);
echo $text;
str_replace is static. Use preg_replace with a regex and you can accomplish your task.
Something like:
$text = "[code:54as] [/code]";
echo preg_replace('~(\[/?.*?):.*?\]~', '$1]', $text);
Should do it.
PHP Demo: https://eval.in/643544
Regex demo: https://regex101.com/r/mD1bM3/1
If you only want to replace numbers and letters after the : use a character class in place of the second .*?. [A-Za-z\d]*?.

How to replace string with tags used

I want to replace the string "<Reason/>" with empty space or just nothing.
I tried str_replace('<Reason/>','',$string) but it won't take the tags.
I tried str_preg('<Reason/>','', $string) but it leaves the the tags "<>".
I tried str_preg('/^<Reason/>/','', $string) but its gives me exception with unknown modifier '>'.
What can I do to remove the whole string along with tags "<Reason/>"?
You probably forgot to assign the result back to the original variable.
The following code works:
$string = str_replace('<Reason/>','',$string);
Full example:
$string = '<Reason/>lalala<Reason/>';
$string = str_replace('<Reason/>','',$string);
echo $string;
Output
lalala
for Case Insensitive, use
str_ireplace()
instead of `
str_replace()
`

Make user name bolded in text in PHP

$text = 'Hello #demo here!';
$pattern = '/#(.*?)[ ]/';
$replacement = '<strong>${1}</strong> ';
echo preg_replace($pattern, $replacement, $text);
This works, I get HTML like this: Hello <strong>demo</strong> here!. But this not works, when that #demo is at the end of string, example: $text = 'Hello #demo';. How can I change my pattern, so it will return same output whenever it is end of the string or not.
Question 2:
What if the string is like $text = 'Hello #demo!';, so it will not put ! as bolded text? Just catch space, end of string or not real-word.
Sorry for bad English, hope you know what I need.
In order to select a word beginning with the # symbol, this regex will work:
$pattern = "/#(\w+)\b/"
`\w` is a short hand character class for `[a-zA-Z0-9_]`. `\b` is an anchor for the beginning or end of a word, in this case the end. So the regex is saying: select something starting with an '#' followed by one or more word characters until the end of the word is reached.
Reference: http://www.regular-expressions.info/tutorial.
You could use a word boundary, that's what they're for:
$pattern = '/#(.+?)\b/';
This will work for question 2 also
You can add an option to match the end of the string:
#(.*?)(?= |\p{P}?$)
Replace with <strong>$1</strong>.
You can also use \p{P} (any Unicode punctuation symbol) to prevent punctuation from bold formatting.
Here is a demo.

PHP preg_match & preg_replace outputing wrong

<?php
$string = "[img image:left]1.jpg[/img]Example Text 1[img image:left]2.jpg[/img] Example Text 2";
preg_match("/\[img\s*[^>]+\s*\](.*?)\[\/\s*img\]/i", $string, $match);
$result = preg_replace("/\[img\s*[^>]+\s*\](.*?)\[\/\s*img\]/i", $match['1'], $string);
echo $result;
?>
When using this code it should output 1.jpg, Example Text 1, 2.jpg, Example Text 2.
But however it shows only 2.jpg, Example Text 2.
I dont know what i'm doing wrong.
There are two fundamental issues:
you don't need to use a preg_match() and a preg_replace(), you can just use preg_replace() and reference your capture groups in the substitution
it looks like you copy pasted some code from HTML regex, and have [^>]+ inside of your [img], which says 1+ non-> characters..it should really be [^\]]+, 1+ non-] characters
Final solution:
$string = "[img image:left]1.jpg[/img]Example Text 1[img image:left]2.jpg[/img] Example Text 2";
$string = preg_replace("/\[img\s*[^\]]+\s*\](.*?)\[\/\s*img\]/i", ' \1 ', $string);
Demo: RegEx and PHP

remove double square brackets and keep the string

I need to remove all square brackets from a string and keep the string. I've been looking around but all topic OP's want to replace the string with something.
So: [[link_to_page]]
should become: link_to_page
I think I should use php regex, can someone assist me?
Thanks in advance
You can simply use a str_replace.
$string = str_replace(array('[[',']]'),'',$string);
But this would get a '[[' without a ']]' closure. And a ']]' without a '[[' opening.
It's not entirely clear what you want - but...
If you simply want to "remove all square brackets" without worrying about pairing/etc then a simple str_replace will do it:
str_replace( array('[',']') , '' , $string )
That is not (and doesn't need to be) a regex.
If you want to unwrap paired double brackets, with unknown contents, then a regex replace is what you want, which uses preg_replace instead.
Since [ and ] are metacharacters in regex, they need to be escaped with a backslash.
To match all instances of double-bracketed text, you can use the pattern \[\[\w+\[\] and to replace those brackets you can put the contents into a capture group (by surrounding with parentheses) and replace all instances like so:
$output = preg_replace( '/\[\[(\w+)\[\]/' , '$1' , $string );
The \w matches any alphanumeric or underscore - if you want to allow more/less characters it can be updated, e.g. \[\[([a-z\-_]+)\[\] or whatever makes sense.
If you want to act on the contents of the square brackets, see the answer by fluminis.
You can use preg_replace:
$repl = preg_replace('/(\[|\]){2}/', '', '[[link_to_page]]');
OR using str_replace:
$repl = str_replace(array('[[', ']]'), '', '[[link_to_page]]');
If you want only one match :
preg_match('/\[\[([^\]]+)\]\]/', $yourText, $matches);
echo $matches[1]; // will echo link_to_page
Or if you want to extract all the link from a text
preg_match_all('/\[\[([^\]]+)\]\]/', $yourText, $matches);
foreach($matches as $link) {
echo $link[1];
}
How to read '/\[\[([^\]]+)\]\]/'
/ start the regex
\[\[ two [ characters but need to escape them because [ is a meta caracter
([^\]]+) get all chars that are not a ]
\]\] two ] characters but need to escape them because ] is a meta caracter
/ end the regex
Try
preg_replace(/(\[\[)|(\]\])/, '', $string);

Categories