0

With the following string:

$string='some text <photo id="id#" /> some text';

Make a substr that if the end of its string is a part of

<photo id="id#" />

then apply an extra chunk to complete

"<photo id="id#" />"

Example:

substr($string,0,15);

result is:

some text <phot

If this happens I need to end up with:

some text <photo id="id#" />

He, can't find the way of doing this. by the way id# is a random numeric value whose length won't exceed 3 chars. If regex is necessary to come up with a function.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Pablo Colla
  • 217
  • 1
  • 9
  • 1
    Have you considered a DOM parser? – Brad Aug 28 '12 at 17:40
  • The tag you need to care of is just photo or yuou have to care about different ones too? – Eineki Aug 28 '12 at 17:44
  • 1
    Please refrain from parsing HTML with RegEx as it will [drive you į̷̷͚̤̤̖̱̦͍͗̒̈̅̄̎n̨͖͓̹͍͎͔͈̝̲͐ͪ͛̃̄͛ṣ̷̵̞̦ͤ̅̉̋ͪ͑͛ͥ͜a̷̘͖̮͔͎͛̇̏̒͆̆͘n͇͔̤̼͙̩͖̭ͤ͋̉͌͟eͥ͒͆ͧͨ̽͞҉̹͍̳̻͢](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). Use an [HTML parser](http://stackoverflow.com/questions/292926/robust-mature-html-parser-for-php) instead. – Madara's Ghost Aug 28 '12 at 18:19
  • I only need to care about the photo tag – Pablo Colla Aug 28 '12 at 18:29
  • I am not parsing html, is a value from a database. – Pablo Colla Aug 28 '12 at 18:30

2 Answers2

2

See this:-

output:-

enter image description here

<?php

$str= 'some text <photo id="#xx"/> some test';
$parts = preg_split('~(</?[\w][^>]*>)~', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
echo '<pre>';
print_r($parts);
echo htmlentities($parts[1]);


$str_new= 'some text <photo id="#xx"></photo> some test';
$parts_new = preg_split('~(</?[\w][^>]*>)~', $str_new, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
echo '<pre>';
print_r($parts_new);
echo htmlentities($parts_new[1]);
echo htmlentities($parts_new[2]);

?>
Abid Hussain
  • 7,724
  • 3
  • 35
  • 53
0

No need to use regex, just use the PHP string functions:

$string = 'some text <photo id="id#" /> some text';
$newString = substr($string, 0, strpos($string, '>') + 1);
Alex Kalicki
  • 1,533
  • 9
  • 20