0

i am currently trying to convert this code:

private static String CutOutXML(string resp)
{
        var url = resp.Substring(resp.IndexOf("<div>") + "<div>".Length);
        url = url.Substring(0, url.IndexOf("</div>"));
        return url;
}

to PHP, but this isn't working:

$startpos = strrpos($correcthtml, '<div>');
$correcthtml = substr($correcthtml, $startpos);
$stoppos = strrpos($correcthtml, '</div>');
$correcthtml = substr($correcthtml, $stoppos);

i am trying to curl a web url from the internet and i only need one xml tag out of it. I am now trying for so long and i dont come behind it how to do this.

  • Does this answer your question? [PHP: Regular Expression to get a URL from a string](https://stackoverflow.com/questions/2720805/php-regular-expression-to-get-a-url-from-a-string) – ba-a-aton Jun 08 '21 at 12:06
  • This can get very complicated quickly. What does _$correcthtml_ contain? A full website? A single, simple XML string? – waterloomatt Jun 08 '21 at 12:09
  • No a Full Website, but the html tags are set correctly and in C# this works – Flori00312 Jun 08 '21 at 12:12
  • How is it "not working"? Unexpected result? No result? Error? – Fildor Jun 08 '21 at 12:15
  • Mind that in the C# version you add the length of `
    ` to the position for first substring.
    – Fildor Jun 08 '21 at 12:16
  • And in the second `substr` you get the part of the string starting at the position of `` _to the end of the string_. While what you want is the substring from 0 _to_ that position. So try `$correcthtml = substr($correcthtml, 0, $stoppos);` – Fildor Jun 08 '21 at 12:18
  • You have HTML (not XML). Remove the XMLfrom this posting. – jdweng Jun 08 '21 at 13:11

1 Answers1

1

the translation of

private static String CutOutXML(string resp)
{
    var url = resp.Substring(resp.IndexOf("<div>") + "<div>".Length);
    url = url.Substring(0, url.IndexOf("</div>"));
    return url;
}

would be

function CutOutXML(string $resp):string
{
    $url = substr($resp,strrpos($resp,'<div>')+ strlen('<div>'));
    $url = substr($url,0, strrpos($url,"</div>"));
    return $url;
}

however as the other comments say there are much better ways of doing what you appear to be trying to do

eg

$matches = [];
preg_match('/<div>(.*)<\/div>/', $resp, $matches);
print_r($matches);
MikeT
  • 5,398
  • 3
  • 27
  • 43
  • php uses both ' and " to delimit string ' is for absolute string " for string that allow interpolation as neither string includes a $ then shouldn't make a difference – MikeT Jun 08 '21 at 12:24
  • Ok, thx. Was just wondering because one time ' , one time ". But alrighty then. – Fildor Jun 08 '21 at 12:27
  • 1
    in c# `'` would be `@""` and `"` would be `$""` – MikeT Jun 08 '21 at 12:30