0

I have the below simple replace working

<?php
$mydata= '15-2003';
$pattern = '/[-]/';
$replacement = ' ';
echo preg_replace($pattern, $replacement, $mydata);
?>

Which outputs 15 2003

However when I put it in my foreach loop it doesn't seem to work?

I have this

<?php foreach ($tests as $test): ?>
<tr>
<?php
$mydata= htmlout($test['f']);
$pattern = '/[-]/';
$replacement = '';
echo preg_replace($pattern, $replacement, $mydata);
?>
<?php endforeach; ?>

Which outputs 15-2003 Where am I going wrong here?

htmlout is the below custom function.

<?php
function html($text)
{
return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}
function htmlout($text)
{
echo html($text);
}

When I do var_dump($mydata); I get NULL

7
  • please show what $tests contains Commented Jul 16, 2012 at 12:38
  • 2
    For such a simple replacement, str_replace() will do the job just fine. I also note that in your looping example you are replacing with an empty string instead of a space like your first example. Commented Jul 16, 2012 at 12:38
  • You know that you could use str_replace here, right? Commented Jul 16, 2012 at 12:38
  • 2
    what is htmlout and what does it return? (if this is converting to unicode you may not be replacing the same hyphen you think you are...) Commented Jul 16, 2012 at 12:39
  • First, for such a simple replace you should use str_replace, which is faster. Can you do a simple var_dump($mydata); ? Commented Jul 16, 2012 at 12:40

1 Answer 1

1

This doesn't work as intended because htmlout() echoes the value instead of returning it.

Consider replacing

$mydata= htmlout($test['f']);

with

$mydata= html($test['f']);

What happends in your code is that it simply prints out the original string, returns NULL to $mydata and then you echo a NULL which doesn't show anything.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I understand now. Now I have this working I will change from preg_replace to str_replace()

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.