0

I want to replace a repetitive word of an array, so I do this:

$thisarray = preg_replace ("/HELLO/"), "BYE", $thisarray);

echo $thisarray[0];

That works perfect... the problem comes when I use a PHP SIMPLE HTML DOM PARSER instruction "plaintext"

$thisarray = preg_replace ("/HELLO/"), "BYE", $thisarray);

echo $thisarray[0]->plaintext;

It says: Notice: Trying to get property of non-object in

1
  • 1
    var_dump($thisarray) and find out if plaintext exists Commented Dec 9, 2012 at 15:08

2 Answers 2

2

$thisarray is either an array of strings or an array of simple_html_dom instances. Pick one.

If it's the former, they won't even be objects, and thus can't have a plaintext property.

And if it's the latter, be careful passing it to a function that expects strings. A function that wants strings will either choke on objects or stringify them as needed. Even assuming a simple_html_dom knows how to convert itself to a string, preg_replace will return a string (or an array of strings) as well. That means once preg_replace does its thing and you replace $thisarray with the return value, no matter what it was before, now you have an array of strings. See above.

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

2 Comments

Not to mention this code could never possibly run anyway, given the syntax error.
Yeah, there's that too. But i assume that was just a typo, given that the code ran far enough to throw an error about non-object properties.
0

First of all, preg_replace is not a function that is performant if you just want to replace a world instead of a pattern. For your case, str_replace is better.

Then, you just misuse $thisarray variable. Before your function, it is an object, after, it is no longer an object as preg_replace returns a string OR an array.

so, you can have sort of cleaner code with that :

$textToReplace = array('/HELLO/','other world to replace');
replacementText = array('BYE','other replacemnt text');
$cleanText = str_replace($textToReplace,$replacementText,$thisarray[0]->plaintext);
echo $cleanText;

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.