Jump to content

A little substr, strpos help


DamienRoche

Recommended Posts

I have no idea how to work these substrings despite reading a bit of the documentation I just can't get my head around it.

 

I have this filename:

(2)text.txt

 

It's a variable - $starfile.

 

But How do I just extract what is between ( and ), namely the 2.

 

Here is what I am using:

$filepick = substr($starfile, strpos($starfile, "("), strpos($starfile, ")"));

 

The output:

 

(2)text

 

Can someone possibly explain what I'm doing wrong and how I should be constructing these substrings.

 

Many thanks for any help.

Link to comment
https://forums.phpfreaks.com/topic/125311-a-little-substr-strpos-help/
Share on other sites

the third parameter is how many characters to go, not the index at which to stop.

 

<?php
$str = '(2)text.txt';
$leftP = strpos($str, '(') + 1;
$rightP = strpos($str, ')');
$contents = substr($str, $leftP, $rightP - $leftP);
echo $contents;
?>

 

But using regex would probably be easier to read.

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.