When extracting text between markers, first confirm that both markers exist and that the ending marker comes after the starting marker. The helper below uses strpos() and substr() defensively.
function between(string $text, string $start, string $end): ?string {
$from = strpos($text, $start);
if ($from === false) return null;
$from += strlen($start);
$to = strpos($text, $end, $from);
if ($to === false) return null;
return substr($text, $from, $to - $from);
}
function my_strip(string $start, string $end, string $text): ?string {
$from = stripos($text, $start);
if ($from === false) return null;
$from += strlen($start);
$to = stripos($text, $end, $from);
if ($to === false) return null;
return substr($text, $from, $to - $from);
}
function my_strip2(string $start, string $end, string $text): ?string {
$from = stripos($text, $start);
if ($from === false) return null;
$to = stripos($text, $end, $from + strlen($start));
if ($to === false) return null;
return substr($text, $from, $to + strlen($end) - $from);
}
$text = "You are welcome to plus2net.com. Learn web programming and PHP here.";
echo my_strip('welcome', 'programming', $text) ?? 'Markers not found';
echo "\n";
echo my_strip2('welcome', 'programming', $text) ?? 'Markers not found';
The first helper omits the markers (welcome and programming); the second retains them. If either marker is missing or out of order, each helper returns null. <type>PHP programmer</type>
<name>Your name is here</name>
For a simple text illustration, use <name> and </name> as markers. For real XML documents, use an XML parser rather than string matching, because attributes, namespaces and nested elements can break delimiter-based extraction.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| RottNKorpse | 19-09-2009 |
| Thanks a lot for this...exactly what I was looking for. | |
| elden walden | 30-01-2010 |
| great info-will use to change data in classified ad app. | |
| prakash | 07-01-2013 |
| very good information really it helped me. | |