user1044994
user1044994

Reputation: 89

preg_replace array php simple html dom parser

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

Upvotes: 0

Views: 470

Answers (2)

cHao
cHao

Reputation: 86506

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

Upvotes: 2

artragis
artragis

Reputation: 3713

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;

Upvotes: 0

Related Questions