-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.

3

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.