Asked  7 Months ago    Answers:  5   Viewed   37 times

Despite using PHP for years, I've never really learnt how to use expressions to truncate strings properly... which is now biting me in the backside!

Can anyone provide me with some help truncating this? I need to chop out the text portion from the url, turning

<a href="link.html">text</a>


<a href="link.html"></a>


$str = preg_replace('#(<a.*?>).*?(</a>)#', '$1$2', $str)
Wednesday, March 31, 2021
answered 7 Months ago

You cannot do this reliably. There is no guarantee that // at any position in a file indicates a comment in PHP context. It might very well be contained in a string for example.

It's only possible to approach this with a few concessions. For example if it is sufficient if it catches // comments on a single line, then this would be an option with less false positives:

$source = preg_replace('#^s*//.+$#m', "", $source);

The real solution would be utilize a language parser, but that's obviously overkill. So try with adding some heuristics to avoid removing wrong occourences.

Wednesday, March 31, 2021
answered 7 Months ago

You need to set the amount of time curl gets to complete its operations with curl_setopt.

The CURLOPT_TIMEOUT setting to be specific.

curl_setopt($ch, CURLOPT_TIMEOUT, 400); // the timeout in seconds

Saturday, May 29, 2021
answered 5 Months ago

This will read in only 1900 and 2000 ranged dates.

Saturday, May 29, 2021
answered 5 Months ago

Use a DOM parser instead of a regex if you want to extract data from a HTML or XML document. While a regex will work in simple cases too, it can get weird if the use case gets more complicated or the input data changes in an unexpected way. A DOM parser is more stable and convenient for that purpose.

Example code:

$doc = new DOMDocument();
$doc->loadHTML('Hello <b>ABCD</b> World');

foreach($doc->getElementsByTagName('b') as $element) {
    echo $element->nodeValue;
Saturday, May 29, 2021
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :