• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 440
  • 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
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

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