views:

34

answers:

3

Question is in the title. I tried strip_tags, but that shows up blank and I tried using preg_replace, but I don't quite understand the syntax apparently..

Tried this

    $test = "Home<i>\r</i><i>\n</i>";       
$patterns = array();
$patterns[0] = '<i>';
$test = preg_replace($patterns, '', $test);

but echo $test is still the same!

A: 

strip_tags would return XX\r\n, so preg_replace would probably be what you're looking for, assuming it can actually do what you want to do. I don't know myself whether or not it will strip the tags like you want, but if you just don't understand the syntax, read up here.

Hope this helps.

31eee384
+4  A: 

if you want to just get the first part of the string up to the first tag, how about something like:

$test = "Home<i>\r</i><i>\n</i>";
preg_match('/^[^<]+/', $test, $match);
echo $match[0];

if you want to remove all tags, strip_tags should do it, or you can use preg_replace like:

$test = "Home<i>\r</i><i>\n</i>";
$test = preg_replace('/<[^>]+?>/', '', $test);
echo $test;
Jonathan Kuhn
I like the preg_match one myself, sepecially if you know what XX is in the original question.
Tim
A: 

The problem with your syntax on preg_replace() is that you did not define the pattern as an accurate regular expression. Your method would work if you used str_replace(), but for preg_replace(), the correct pattern for identifying <i> is '/<i>/'. Basically, you need to enclose it in / chars to define it as a regex.

Jonathan's expression is much better than a pattern by pattern implementation, if you are looking to remove all tags. If not, you can handle specific tags like this:

$test = "Home<i>\r</i><i>\n</i>";       
$patterns = array();
$patterns[0] = '/<\/?i>/'; //removes <i> and </i>
$patterns[1] = '/\r|\n/'; //removes \r and \n
$test = preg_replace($patterns, '', $test);
JGB146
the patterns are incorrect. the first one [0] should be `'/<\/?i>/'` and the second one [1] should be `'/\r|\n/'`. It might just be SO removing slashes or something on the second one. but the way it shows you escape the square brace and you were probably thinking of the parenthesis for a group, not the braces to say any of these (r|n) chars. Also if the only thing you are doing is an OR of multiple things, you don't even need the grouping. Grouping is really only useful if you are comparing that group with something else like maybe a `'/<\/?(b|i|u|small|strong|etc)>/'`.
Jonathan Kuhn
You're absolutely right. I guess I made the wrong choice last night when I was deciding between browsing questions and sleep. Adjusted the patterns accordingly.
JGB146