Since you have a "condition" for the age to be displayed, therefore you will have to use PHP if else
to check the date. Below is the code that you can use along with the explanation.
Assuming that the below is the string what you get from your db field.
$fetched_string = '<p> My Smith from <span class="var" id="town">Manchester, aged, <span >class="var" id="age">54</span>';
Now you have to extract the age, which is always in between id="age">
and </span>
The best way to do this is by creating a PHP function for this.
function str_between($string, $searchStart, $searchEnd, $offset = 0) {
$startPosition = strpos($string, $searchStart, $offset);
if ($startPosition !== false) {
$searchStartLength = strlen($searchStart);
$endPosition = strpos($string, $searchEnd, $startPosition + 1);
if ($endPosition !== false) {
return substr($string, $startPosition + $searchStartLength, $endPosition - $searchStartLength);
}
return substr($string, $startPosition + $searchStartLength);
}
return $string;
}
Now you simply have to pass the string values on the left (which will be the searchStart) and the right (searchEnd) of the fetched age. Below is the code to do this.
$fetched_age = str_between($fetched_string, 'id="age">', '</span>');
Based on this, I have revised the final code that you can use as is.
//To get the data from a URL, $_GET method is used. First you will check if the "age" has been set in the URL or not. This is done by:
function str_between($string, $searchStart, $searchEnd, $offset = 0) {
$startPosition = strpos($string, $searchStart, $offset);
if ($startPosition !== false) {
$searchStartLength = strlen($searchStart);
$endPosition = strpos($string, $searchEnd, $startPosition + 1);
if ($endPosition !== false) {
return substr($string, $startPosition + $searchStartLength, $endPosition - $searchStartLength);
}
return substr($string, $startPosition + $searchStartLength);
}
return $string;
}
//Fetched String for db
$fetched_string = $row['full_string'];
//This will give you the age
$fetched_age = str_between($fetched_string, 'id="age">', '</span>');
if (isset($_GET['age'])) {
//If age is set in the URL, assign it to the PHP Variable
$age_display = $_GET['age'];
}
else {
//If age is not set, then assign the age fetched from the db.
$age_display = $fetched_age;
}
Is this what you are looking for?