-1
<?php

$str = htmlspecialchars('<nav><a>something</a></nav>');

$pattern = htmlspecialchars('/<nav><a>something</a></nav>/i');

echo htmlspecialchars(preg_replace($pattern, '<nav> <a href="hi">click</a> 

</nav>', $str));

?>

I need PHP to echo like this:

<nav> <a href="hi">click</a> </nav>

But it's showing this error:

Warning: preg_replace() expects parameter 4 to be int, string given in /opt/lampp/htdocs/Workaera/Sample.php on line 19

2
  • There is no pattern in $pattern. Try stripos() instead of preg_replace. Commented Feb 4, 2021 at 7:37
  • <nav><a>something</a></nav> this is the required pattern mentioned, Commented Feb 4, 2021 at 7:46

3 Answers 3

1

You forgot to escape slashes. This code works:

$str = htmlspecialchars('<nav><a>something</a></nav>');

$pattern = htmlspecialchars('/<nav><a>something<\/a><\/nav>/i');

echo htmlspecialchars(preg_replace($pattern, '<nav> <a href="hi">click</a> 

</nav>', $str));

?>

But in your case preg_replace is probably overkill. Try just str_replace instead:

$str = htmlspecialchars('<nav><a>something</a></nav>');

$pattern = htmlspecialchars('<nav><a>something</a></nav>');

echo str_replace($str, $pattern, '<nav> <a href="hi">click</a> 

</nav>', $str);
Sign up to request clarification or add additional context in comments.

1 Comment

Right. But OP have a /i modifier. Maybe use str_ireplace() instead.
0

Your pattern is not valid, because of the unescaped forward slashes in HTML closing tags.

What you should be doing is something like

//escape HTML
$htmlEscapedPattern = htmlspecialchars('<nav><a>something</a></nav>');
//escape slashes
$forwardSlashEscapedPattern = str_replace("/", "\/", $htmlEscapedPattern);
//wrap as regex pattern
$pattern = "/" . $forwardSlashEscapedPattern . "/i";

1 Comment

You should provide more information then, as this snippet returns the exact result you are expecting. Also note that in your original code you are printing escaped HTML with htmlspecialchars, but in the expected output the HTML is not escaped. If that is the problem just echo without escaping, e.g echo preg_replace($pattern, '<nav> <a href="hi">click</a> </nav>', $str);
0

use the following php code to get your desired result.

$str = htmlspecialchars('<nav><a>something</a></nav>');
$pattern = htmlspecialchars('/<nav><a>something<\/a><\/nav>/i');
echo htmlspecialchars(preg_replace($pattern, '<nav> <a href="hi">click</a> </nav>', $str));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.