Jump to content

Extract values from xpath type string


chazmus

Recommended Posts

Hello,

 

I'd like to be able to change a string that looks like

 

/root/section/subsection/... (potentially alot more sections)

 

so that

$first = "root"

$rest = "/section/subsection/"

 

The string I gave is just an example, in reality there could be many different names for sections, and the first bit won't always be "root" and could be any length..

I have been googling for about an hour now and can't make any sense of regular expressions!

 

Thanks if you can help :)

 

Link to comment
https://forums.phpfreaks.com/topic/187071-extract-values-from-xpath-type-string/
Share on other sites

As much a fan of regular expressions as I am (ask anyone here), sometimes basic string functions will suffice. Indeed, there are a number of different string functions that could be employed here to do the job!

 

Coming to the rescue today is the under-rated and misunderstood strtok function. The snippet below takes the (x)path and hunts around for the first item and then "everything else", allocating those values to their appropriate variable.

 

$path  = '/root/section/subsection/etc';
$first = strtok($path, '/');
$rest  = '/' . strtok('');
var_dump($first, $rest);

 

If you really want a regular expression solution, or don't really feel like using strtok and would prefer other string functions, do let us know.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.