Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Explode - Implode Arrays is ASP 2

Status
Not open for further replies.

jedel

Programmer
Jan 11, 2003
430
0
0
AU
Hey all,

I am wondering if there is anything like Explode or Implode function used in PHP for ASP?

What I would like to do is take a chunk of data from a memo field in an Access database, say; the first 20 words, and display it on the page. This way when the user tries to write a novel, it will only display the first 20 words and not look out of place with the rest of the web page.

I use this piece of code in PHP and was just wondering if there is a way of doing the same thing in ASP?
Code:
function strip_text($str,$start,$end)
    {
        $body = explode(" ",$str);
        $intstr = array_slice($body,$start,$end);
        $newstr = implode(" ", $intstr);
        return $newstr;
        }


-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
You can split it by the space and return the first x number of words...if the string is shorter than x number of words, the entire string will get returned.

where strInput is the string you want to shorten and intWords is the number of words you want to shorten it to.

Code:
function shorten(strInput,intWords)
  raWords = split(strInput," ")
  for ndx = 0 to ubound(raWords)
    strReturn = strReturn & " " & raWords(ndx)
    if ndx = intWords then exit for
  next
  erase raWords
  shorten = strReturn
end function

TIP: trying googling the answer before posting, you'll find that more times than not someone else somewhere has had the same request and posted an answer online.
----
I have recently been semi-converted to ensuring all my code (well most of it) works in both javascript and non-javascript enabled browsers
 
vicvirk

I can see how that works, now how do I call the code on the page? This is what I tried:

<%Response.Write(shorten((ComingUp.Fields.Item("Short Description").Value),20))%>

Got a Type Mismatch error

I placed your code in the header of the page

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
Jedel,

The code can be placed anywhere on the page, it does need to be enclosed within <% %>

Can you provide some more code above and below what you're using to call it?

The way I would normally do it is:

Code:
<%
' get the value from the db recordset
strValue = rsComingUp("short_description")
' convert it and display it
response.write shorten(strValue,20)
%>

I ran this code and it works for me (I made a couple of tweaks:

1. Put in a condition so that if there are less words than requested, the entire string gets returned and no array needs to be built.

2. Changed the loop to go minus one from the "intWords" paramater (the array is zero based)

Code:
<%
function shorten(strInput,intWords)
	raWords = split(strInput," ")
	if ubound(raWords) <= intWords then
		strReturn  = strInput
	else
		for ndx = 0 to intWords - 1
		strReturn = strReturn & " " & raWords(ndx)
		next
	end if
	erase raWords
	shorten = strReturn
end function
%>

<%
strValue = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit."
response.write shorten(strValue,5)
%>

TIP: trying googling the answer before posting, you'll find that more times than not someone else somewhere has had the same request and posted an answer online.
----
I have recently been semi-converted to ensuring all my code (well most of it) works in both javascript and non-javascript enabled browsers
 
Sorry

I copied and pasted your code above, even to the point of using straight text (Lorum Ipsum) etc to see if the code will work on my page, I came up with this error:


Microsoft VBScript compilation error '800a03ea'

Syntax error

/men/index.asp, line 247

function shorten(strInput,intWords)


The little arrow was point directly under the "f" in function

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
^ can you provide (say 25 lines) of code above and below where you put the statement into your page?

I tried it on my end and it works no problem, might be where you have the function located.

Also try creating a new .ASP page and paste the entire code into it and see if you can even execute it.

TIP: trying googling the answer before posting, you'll find that more times than not someone else somewhere has had the same request and posted an answer online.
----
I have recently been semi-converted to ensuring all my code (well most of it) works in both javascript and non-javascript enabled browsers
 
on a less code intensive note : why does it have to be WORDS? why not use an arbitrary truncation length, say the first 200 characters? then slap a "..." at the end of it?

that's done with:
Code:
 response.write Left(String,200) & "..." [code]


[thumbsup2]DreX
aKa - Robert 
[i]if all else fails, light it on fire and do the happy dance![/i]
[i][b]" I always think outside the 'box', because I'm never in the 'loop' "[/b][/i] - DreX 2005
 
DreX,

I've used that in the past, and it works great sometimes, but not always...

The LEFT function returns exactly that, the left 200 chars, but if you have any HTML tags within that code, you could end up with something like this:

"<strong>Lorem ipsum dolor sit amet, consectetuer</st"

Which would essentially break the site.

You could also end up with something like this:

What if the full post is:

strValue = "As I was walking out the front door, I made sure to grab my shitzu and his food before dropping him off at the kennel"

A left(strValue,64)... would return

As I was walking out the front door, I made sure to grab my (you can figure the rest out).







TIP: trying googling the answer before posting, you'll find that more times than not someone else somewhere has had the same request and posted an answer online.
----
I have recently been semi-converted to ensuring all my code (well most of it) works in both javascript and non-javascript enabled browsers
 
DreXor,

SOrry I agree with vicvirk. I do have HTML in the field. Nice thought though.

vicvirk, sorry for the delay, here is the page from the container div tags. I've used Dreamweaver to build the page up. All of the connections to the databsae work fine.

Code:
<div id="container">
  <div id="header"><img src="[URL unfurl="true"]http://www.calvarycc.org.au/images/webheader.png"[/URL] width="1000" height="151" alt="header" /></div>
  <div id = "menu"><span id='awmAnchor-menu'>&nbsp;</span></div>
  <div id="mainContent"><%=(page.Fields.Item("Content").Value)%>
    <!-- end #mainContent -->
  </div>
  <div id="events">
    <table border="0" cellpadding="2">
      <tr>
        <%
  ' Horizontal Looper version 3
  While ((Repeat_events__numRowsHL <> 0) AND (NOT events.EOF))
%>
          <td align="left" valign="top"><span class="medWhiteBold"><%=(events.Fields.Item("DteText").Value)%><br />
            <%=(events.Fields.Item("eventTitle").Value)%></span><br />
                <% if (events.Fields.Item("Detailyes").Value)="Yes" Then
Response.write("<a href='../pages/evnet.asp?" & Server.HTMLEncode(MM_keepURL) & MM_joinChar(MM_keepURL) & "ComingID=" & events.Fields.Item("ComingID").Value & "'><img src='[URL unfurl="true"]http://www.calvarycc.org.au"[/URL] & (events.Fields.Item("Img").Value)& "' width='188' height='100' border='0' /></a>")
Else
Response.Write("<img src='[URL unfurl="true"]http://www.calvarycc.org.au"[/URL] & (events.Fields.Item("Img").Value)& "' width='188' height='100' border='0' />")
End If
%> <br />
[b]<%
function shorten(strInput,intWords)
    raWords = split(strInput," ")
    if ubound(raWords) <= intWords then
        strReturn  = strInput
    else
        for ndx = 0 to intWords - 1
        strReturn = strReturn & " " & raWords(ndx)
        next
    end if
    erase raWords
    shorten = strReturn
end function
%>

<%
strValue = (events.Fields.Item("Short Description").Value)
response.write shorten(strValue,5)
%>[/b]
             <br />


               </td>
          <%
    'Horizontal Looper version 3
    Repeat_events__indexHL=Repeat_events__indexHL+1
    Repeat_events__numRowsHL=Repeat_events__numRowsHL-1
    events.MoveNext()
    if len(nested_events)<=0 then
      nested_events = 1
    end if
    if ((Repeat_events__numRowsHL <> 0) AND (NOT events.EOF) AND (nested_events mod 5 = 0)) then
      Response.Write "</tr><tr>"
    end if
    nested_events = nested_events + 1
    'end horizontal looper version 3
  Wend
%>
      </tr>
    </table>
    
    <!--END EVENTS -->
  </div>
  <div class="clearfloat"></div>
  <div id="footer">
    <!--#include virtual="/includes/churchfooter.asp" -->
    <!-- end #footer -->
  </div>
  <!-- end #container -->
</div>

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
OK Guys, I found the problem. It was in the Repeat region. Once I placed the function outside of the repeat region, away it went.

I guess after writing that, it was a pretty dumb thing to do.

Love the code snippet vicvirk, have a star.

Thanks all for your input

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
After thinking about this a bit more and what DreX posted, you'll need to add some more error checking

Code:
<strong>This is some text</strong> and this is more

if you are returning the first 3 words of the above, you'll end up with

"<strong>This is some"

^ which will break the site as there is no closing tag for the opening <strong>

Also,

Code:
You can find out more by clicking <a href="mysite.html">here</a> to find out more

returning the first 8 words would return

"You can find out more by clicking <a "

^ which is also an "error"

Splitting by words will solve the "shitzu" problem, but won't fully solve the "missing closing tags" problem.

If I have, sorry for bursting your bubble :)


TIP: trying googling the answer before posting, you'll find that more times than not someone else somewhere has had the same request and posted an answer online.
----
I have recently been semi-converted to ensuring all my code (well most of it) works in both javascript and non-javascript enabled browsers
 
You can eliminate the loop if you redim preserve the array after splitting it, and then Joining the array at the end.

The shorten function can be reduced to this:

Code:
Function shorten(strInput, intWords)
		  
    raWords = Split(strInput, " ")
    ReDim Preserve raWords(intWords - 1)
    shorten = Join(raWords, " ")
		  
End Function

Notice that I use intWords-1 to redim it. If you pass the value 0 in to this function, it will error. Suppose you want 5 words, you need to redim the array to the 4th element (0,1,2,3,4). Then, of course, join the results.

-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
George - that's awesome

(*)



TIP: trying googling the answer before posting, you'll find that more times than not someone else somewhere has had the same request and posted an answer online.
----
I have recently been semi-converted to ensuring all my code (well most of it) works in both javascript and non-javascript enabled browsers
 
side note is you're concerned about html if you split on a space, that may be a space between attributes of a given tag, say an INPUT tag.. perhaps would best be resolved with the use of a regex, using < & > boundries, and return a for loop of the first 200 matches, or.. split and resplit an array on > and < i post the resplit function here, it's been a godsend in the past for my development projects, as well as an addtoarray funtion, many uses including initial population of an array in a loop.

Code:
Function AddToArray(OriginArray,AddValue)
  If IsArray(OriginArray) Then
   NewDim = Ubound(OriginArray)+1
   ReDim Preserve OriginArray(NewDim)
   OriginArray(NewDim) = AddValue
   AddToArray = OriginArray
  Else
    AddToArray = Array(OriginArray,AddValue)
  End If
End Function

Function ReSplit(OriginArray, sDelimiter)
  If IsArray(OriginArray) Then
    Dim OutputArray() ,iArrayUpper , FirstInSet , NewUbound 
    NewUbound = -1
    For ArrayPosition = 0 To UBound(OriginArray)
      NewUbound = NewUbound + 1
      SubString = OriginArray(ArrayPosition)
      FirstInSet = InStr(1, SubString, sDelimiter, vbBinaryCompare)
      Do While FirstInSet > 0
        ReDim Preserve OutputArray(NewUbound)
        OutputArray(NewUbound) = Left(SubString, FirstInSet - 1)
        SubString = Right(SubString, Len(SubString) - FirstInSet - Len(sDelimiter)+1)
        FirstInSet = InStr(1, SubString, sDelimiter, vbBinaryCompare)
        NewUbound = NewUbound + 1
      Loop
      ReDim Preserve OutputArray(NewUbound)
      OutputArray(NewUbound) = SubString
    Next
    ReSplit = OutputArray
  Else
    ReSplit = Array("Error")
  End If
End Function

usage is pretty straight foreward :

somearray = split(list of values, some delimiter)
somearray = repsplit(somearray, some other delimiter)
somearray = addtoarray(somearray, new value)


since you're more used to C/Java style environments these might be of some migraine relief. used mostly in the same context of stringvalue += more stuff ( addtoarray)

[thumbsup2]DreX
aKa - Robert
if all else fails, light it on fire and do the happy dance!
" I always think outside the 'box', because I'm never in the 'loop' " - DreX 2005
 
second thought as well and apoligies to vic, i missed your post about open tages without close tags, and blurting out mid tag disruption, guess between the two of us we got half a brain [:)]

second thought was back to the regex, does get a little more code intensive, but if you use a pattern like "<[<+]>" which is a maringally standard html tag strip, you count your first 20 words or whatever, then mark that location, then find that location in the regex matches, then return all the opening tags up to that 20th word, and then rerun the same regexmatches with .replace to include a close tag

tho this turns into a huge regex ordeal because what if it is an <input> tag, there's no close tag for it...

kinda gettin bummed thinking of holes in options, i hate being pessimistic.

will scratch my head more on this though..

[thumbsup2]DreX
aKa - Robert
if all else fails, light it on fire and do the happy dance!
" I always think outside the 'box', because I'm never in the 'loop' " - DreX 2005
 
JS would do nicely on this, cause you can reference the nodes, type and count them and easily close them, and just document.write tag the innerhtml of each and a forced close tag based on the count

..then again ... so would php [sadeyes]

[thumbsup2]DreX
aKa - Robert
if all else fails, light it on fire and do the happy dance!
" I always think outside the 'box', because I'm never in the 'loop' " - DreX 2005
 
Robert,

I agree, and yes, I am working on converting this clients site to php and MySQL, However, they still need to operate and in the meantime, I must still manage their ASP site.

-------------------------------------------------------------
"The most overlooked advantage of owning a computer is that if they foul up there's no law against whacking them around a bit."
 
only thing that comes to mind is a div overflow:clip

though the novels you mentioned earlier would be in full form, only a portion would ve visible, with all it's html intact

<dry><well>me</well></dry>

[thumbsup2]DreX
aKa - Robert
if all else fails, light it on fire and do the happy dance!
" I always think outside the 'box', because I'm never in the 'loop' " - DreX 2005
 
just a retouch on this one, and i think i might have a do-able solution for you, use the regex method/pattern mentioned above, now using the regex.matches collection
get your 200 words or whatnot then recycle the same matches
apply another regex to get the original tag itself only, insert these into an array, then cycle the array in reverse to close all tags, but only if the original tag hadn't been closed before, this can also be done with a counter per tag type, and some conditionals for non-closing tags, <input> etc..


little bit on the extensive side, but should get you the desired results, miht take a lil trial and error, and should i get some free time to chew code i'll try to do a sample.


[thumbsup2]DreX
aKa - Robert
if all else fails, light it on fire and do the happy dance!
" I always think outside the 'box', because I'm never in the 'loop' " - DreX 2005
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top