Question

i have a string that has markers and I need to replace with text from a database. this text string is stored in a database and the markers are for auto fill with data from a different part of the database.

$text = '<span data-field="la_lname" data-table="user_properties">
{Listing Agent Last Name}
</span>
<br>RE: The new offer<br>Please find attached....'

if i can find the data marker by: strpos($text, 'la_lname'); can i use that to select everything in and between the <span> and </span> tags..

so the new string looks like:

'Sommers<br>RE: The new offer<br>Please find attached....'

I thought I could explode the string based on the <span> tags but that opens up a lot of problems as I need to keep the text intact and formated as it is. I just want to insert the data and leave everything else untouched.

Was it helpful?

Solution

To get what's between two parts of a string for example if you have

<span>SomeText</span>

If you want to get SomeText then I suggest using a function that gets whatever is between two parts that you put as parameters

<?php
function getbetween($content,$start,$end) {
$r = explode($start, $content);
if (isset($r[1])){
    $r = explode($end, $r[1]);
    return $r[0];
}
return '';
} 

$text = '<span>SomeText</span>';
$start = '<span>';
$end = '</span>';
$required_text = getbetween($text,$start,$end);
$full_line = $start.$required_text.$end;
$text = str_replace($full_line, 'WHAT TO REPLACE IT WITH HERE',$text);

OTHER TIPS

You could try preg_replace or use a DOM Parser, which is far more useful for navigating HTML-like-structure.

I should add that while regular expressions should work just fine in this example, you may need to do more complex things in the future or traverse more intrincate DOM structures for your replacements, so a DOM Parser is the way to go in this case.

Using PHP Simple HTML DOM Parser

$html = str_get_html('<span data-field="la_lname" data-table="user_properties">{Listing Agent Last Name}</span><br>RE: The new offer<br>Please find attached....');
$html->find('span')->innerText = 'New value of span';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top