[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 430
  • Last Modified:

php string explode 'light' needed

- I need to cut a string (e.g. $sentence) into two parts; I call the first $alpha and the second $beta.

- I cannot use explode, because I would like to split the string only aftter the first occurence of the needed value ($alpha) included within 'separator' "/", and don't want to have an array with more than 2 items.

- Further more, I need the 'separators', n occurences, included (and not removed) in the $beta string.

- the length of $alpha and $beta is not known in advance and variable.

Sample:
$sentence = "/iamhungry/pleasegiveme/frenchfries/"
Expected result:
$alpha: "iamhungry"
$beta: "pleasegiveme/frenchfries/"
0
swissoffice
Asked:
swissoffice
1 Solution
 
Beverley PortlockCommented:
Try this

<?php

     $sentence = "/iamhungry/pleasegiveme/frenchfries/";

     $pattern = '#/([^/]+)/?(.*)#';

     preg_match( $pattern, $sentence, $match );
     $resultArray = array_slice( $match, 1, 2 );
     
     print_r( $resultArray );

Open in new window


which produces

Array
(
    [0] => iamhungry
    [1] => pleasegiveme/frenchfries/
)
0
 
Slick812Commented:
greetings swissoffice,, , , not sure if I understood your requirements completely. . ., but here is a sentence splitter, that uses the first character of the sentence for the split delimiter.

I have changed the / to a + in the second sentence to show that it does different delimiters.

ask questions if you need more info about it.
<?php

//$sentence = '/iamhungry/pleasegiveme/frenchfries/';
$sentence = '+iamhungry+pleasegiveme+frenchfries+';
if ($pos = strpos($sentence, $sentence{0}, 1)) {
	$aryAlpha = array();
	$aryAlpha[] = substr($sentence,1, $pos-1);
	$aryAlpha[] = substr($sentence,$pos+1);
	//echo 'first- '.$aryAlpha[0].' -next- '.$aryAlpha[1].'<br />';
	var_dump ($aryAlpha);
	} else echo 'Error string does not contain second delimiter';

?>

Open in new window

0
 
swissofficeAuthor Commented:
Thank you guys; I will need some time to understand and test it; for info (slick812), the sentence delimiter will always be /; and there is always one at the beginning; however, not sure if there will be $beta -  something after $alpha (a $Sentence "/iamhungry/" or "/iamhungry" could be possible - I planned to treat this in a second time after having split into $alpha and $beta first).
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Beverley PortlockCommented:
The regular expression version that I gave above will work even if $beta is empty. Using

$sentence = "/iamhungry";

gives

Array
(
    [0] => iamhungry
    [1] =>
)

To make it work with delimiters other than /


     $sentence = "+iamhungry+pleasegiveme+frenchfries+";
     $delim    = '\+';

     $pattern = '#'.$delim.'([^'.$delim.']+)'.$delim.'?(.*)#';


Note that I had to escape the '+' as '\+' since it has a special meaning in regular expressions as does *, ?, dot, [, ], ( and )
0
 
Mohamed AbowardaSoftware EngineerCommented:
Well, you can use explode() to do what you want!

Here is the code:
 
$sentence = "/iamhungry/pleasegiveme/frenchfries/";
if (!$sentence[0] == '/')
	$str = '/' . $sentence;
else
	$str = $sentence;

$arr = explode('/', $str);
$alpha = $arr[1];
unset($arr[0]);
unset($arr[1]);
foreach ($arr as $item)
{
	if ($beta != '')
		$beta .= "/";
	$beta .= $item;
}

echo "Alpha: $alpha<br />";
echo "Beta: $beta";

Open in new window


Output:
 
Alpha: iamhungry
Beta: pleasegiveme/frenchfries/

Open in new window

0
 
swissofficeAuthor Commented:
Ok, thanks. A feeling tells me that slicks solution isn't competitive enough; Here's the challange for bportlock and Medo3337: which solution requires less server ressources, i.e. is faster?
0
 
Beverley PortlockCommented:
"which solution requires less server ressources, i.e. is faster?"

It's the wrong question to ask, but I'll answer it anyway. Regexes are typically 5 to 7 times lower than string operations. Sounds bad doesn't it? Think about this - on most servers these operations are measured in microseconds - millionths of a second - so a regex might take 100 microseconds as opposed to 20 microseconds. The web page produced will then a FEW SECONDS to download to the browser so the time saved on the string operations is lost and is meaningless

The CORRECT question to ask, IMHO, is "which solution is more robust, easier to maintain and suits my programming style?". The regex is simple, short and concise but the other solution might suit your programming style better.

Forget "speed". With the servers in use these days, worrying about the speed of op-codes and functions is pointless in 99.999% o programming situations.
0
 
swissofficeAuthor Commented:
Thank you for your guidance. You make my life easier.
0
 
swissofficeAuthor Commented:
You guys rock!
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now