Karls
Karls

Reputation: 65

PHP and Simple DOM HTML Parser - Replace identical text string

I'm using the Simple DOM html parser php script in what seems to be a simple way, here's my code:

include('simple_html_dom.php');

$html = file_get_html($_SERVER['DOCUMENT_ROOT']."/wp-content/themes/genesis-sample-develop/cache-reports/atudem.html");

$snow_depth_min = $html->find('td', 115);
$snow_depth_max = $html->find('td', 116);
$snow_type = $html->find('td', 117);

The problem is with $snow_type. Sometimes the parsed text string is 'polvo' and sometimes it is 'polvo-dura'. I'm trying to replace 'polvo' with 'powder', and 'polvo-dura' with 'powder/packed'. If I do something like

if ($snow_type->innertext=='polvo-dura') {
    $snow_type->innertext('powder');
}

or

$snow_type = str_replace("polvo", "powder", $snow_type);
$snow_type = str_replace("polvo-dura", "powder/packed", $snow_type);

it ends up with results like 'powder-dura' and weird things like that.

Obviously I'm new to php, so have some pattience with me ;) I would also like to understand why this happens and why a possible solution would work.

Thanks in advance

Upvotes: 0

Views: 287

Answers (2)

Karls
Karls

Reputation: 65

Provisional solution, using indexed arrays with preg_replace() :

$patterns = array();
    $patterns[0] = '/-/';
    $patterns[1] = '/polvo/';
    $patterns[2] = '/dura/';
    $replacements = array();
    $replacements[0] = '/';
    $replacements[1] = 'powder';
    $replacements[2] = 'packed';

    $snow_type_spanish_english = preg_replace($patterns, $replacements, $snow_type);

I have serious concerns about how it would work in real-world long complex texts, but for short-type data such as 'snow type' with values like 'a', 'b', 'a/b' or 'b/a', this can be just fine.

It would be great if someone comes with a better solution. I've been searching all over Internet for days and haven't found any specific solutions for text-values with the same words at the beginning, like 'powder' and 'powder-packed' for example.

Upvotes: 0

Krishna Gupta
Krishna Gupta

Reputation: 685

if ($snow_type->innertext=='polvo-dura') {
    $innertext = 'powder/packed';
} else if ($snow_type->innertext=='polvo') {
    $innertext = 'powder';
}

Upvotes: 1

Related Questions