-1

I have a string, that look like this "<html>". Now what I want to do, is get all text between the "<" and the ">", and this should apply to any text, so that if i did "<hello>", or "<p>" that would also work. Then I want to replace this string with a string that contains the string between the tags. For example
In:

<[STRING]>

Out:

<this is [STRING]>

Where [STRING] is the string between the tags.

Franz Gleichmann
  • 3,420
  • 4
  • 20
  • 30
David Wolters
  • 336
  • 2
  • 6
  • 18
  • http://php.net/manual/en/function.strip-tags.php – Farkie Nov 23 '16 at 19:20
  • 1
    i'd say you should take a look at regular expressions, but you already tagged them. so instead i'm gonna ask: and what have you *tried* so far? – Franz Gleichmann Nov 23 '16 at 19:20
  • 2
    [Are you parsing html with a regular expression?](http://stackoverflow.com/a/1732454/1641867) - don't think thats a good idea. – ventiseis Nov 23 '16 at 19:23
  • Possible duplicate of [Regex - Matching Tag Names Only in HTML](http://stackoverflow.com/questions/7181653/regex-matching-tag-names-only-in-html) – ventiseis Nov 23 '16 at 19:25

3 Answers3

2

Use a capture group to match everything after < that isn't >, and substitute that into the replacement string.

preg_replace('/<([^>]*)>/, '<this is $1>/, $string);
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

here is a solution to test on the pattern exists and then capture it to finally modify it ...

<?php
$str = '<[STRING]>';
$pattern = '#<(\[.*\])>#';

if(preg_match($pattern, $str, $matches)):
    var_dump($matches);
    $str = preg_replace($pattern, '<this is '.$matches[1].'>', $str);
endif;

echo $str;
?>

echo $str; You can test here: http://ideone.com/uVqV0u

0

I don't know if this can be usefull to you. You can use a regular expression that is the best way. But you can also consider a little function that remove first < and last > char from your string.

This is my solution:

<?php

/*Vars to test*/

$var1="<HTML>";
$var2="<P>";
$var3="<ALL YOU WANT>";

/*function*/

function replace($string_tag) {
$newString="";
for ($i=1; $i<(strlen($string_tag)-1); $i++){
    $newString.=$string_tag[$i];
}

return $newString;

}

/*Output*/

echo (replace($var1));
echo "\r\n";
echo (replace($var2));
echo "\r\n";
echo (replace($var3));

?>

Output give me:
HTML
P
ALL YOU WANT

Tested on https://ideone.com/2RnbnY

Yeti82
  • 383
  • 1
  • 6
  • 14