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
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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.